0

I've read code that has snippets similar to this but I obviously forgot the semantics:

        let serve = target || "Hello World";

In other words if target is null, the serve equals Hello World. My goal, since target is null, is to get serve to be Hello Word ...

If I run the function as stated node prints this:

ReferenceError: target is not defined
7
  • 2
    Looks fine to me. Whats the question? Commented May 7, 2018 at 22:02
  • Updated the question ... I Commented May 7, 2018 at 22:04
  • 1
    As the error is trying to tell you, you cannot reference a variable that was never declared. Commented May 7, 2018 at 22:05
  • remove the target if it is not there :) Commented May 7, 2018 at 22:05
  • 1
    @Ole: If you want to be sure that you don't use variables you haven't declared, I'd recommend using eslint. You can set it up to show you errors for things like undeclared variables. Best to keep the code clean and avoid unnecessary checks :) Commented May 7, 2018 at 22:25

3 Answers 3

3

You need to define the variable target first. Here are some examples:

let target;
let serve = target || "Hello World";
console.log(serve); // prints "Hello World";

target = null;
serve = target || "Hello World";
console.log(serve); // still prints "Hello World";

target = "Cat";
serve = target || "Hello World";
console.log(serve); // prints "Cat"

Sign up to request clarification or add additional context in comments.

Comments

2

Using a || b will return b if a is falsy. The falsy values from You Don't Know JS: Types and Grammar - Chapter 4: Coercion are:

  • undefined
  • null
  • false
  • +0, -0, and NaN
  • ""

If you'd like to return the default only when target is null, use:

let serve = target === null ? "Hello World" : target;

Comments

2

target, in your example is not null. It isn't anything: You haven't declared it at all.

let target = null;
let serve = target || "Hello World";
console.log(serve);

Possibly you are thinking of the pattern:

var serve = serve || "Hello World";
console.log(serve);

Which:

  • Uses var to ensure that serve is a declared variable
  • Assigns "Hello World" to serve is some previous code hasn't already assigned it a true value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.