Javascript Function Argument Passing Question 5

Introduction

What is the output of the following code?

function greet(name) {
    name = name || 'guest';
    console.log("Hello " + name);
}

greet("aaa");//from  w  w  w. j a v  a 2 s.c  om
greet();
greet(undefined);
greet(null);
greet(false);


Hello aaa
Hello guest
Hello guest
Hello guest
Hello guest

The || operator gives the operand that can be coerced to true when provided with 2 different data types.

undefined || "hello" ---> hello
null || "hello" ---> hello
false || "hello" ---> hello
"" || "hello" ---> hello
"hi" || "hello" ---> "hi"

You can think that it is setting the default value.




PreviousNext

Related