07_JavaScript: short-circuit evaluation

07_JavaScript: short-circuit evaluation

using &&, || operators

·

2 min read

true && true // true
true && false // false
true || false // true
false || true // true

Ex01. Sample Code

const dog = {
    name: 'siru';
};

function getName(animal) {
    return animal.name;
}

const name = getName(dog); // There is a parameter
console.log(name); //siru

-> What if there is no proper parameter?

const dog = {
  name: 'siru';
};

function getName(animal) {
  return animal.name; //Error(The animal object is undefined)
}

const name = getName(); //No parameter
console.log(name);

-> Solution01 : using if

const dog = {
  name: 'siru';
};

function getName(animal) {
    if (animal) { //check animal 
        return animal.name;
    }
    return undefined;
}

const name = getName(); //Still no parameter
console.log(name); //undefined

-> Solution02 : using &&

const dog = {
  name: 'siru';
};

function getName(animal) {
    return animal && animal.name; // If animal is truthy, use animal.name
}

const name = getName(); //Still no parameter
console.log(name); //undefined
const dog = {
  name: 'siru';
};

function getName(animal) {
    return animal && animal.name; // If animal is truthy, use animal.name
}

const name = getName(dog); // put parameter
console.log(name); //siru

Ex02. Sample Code

const namelessDog = {
    name: '';
};

function getName(animal) {
    const name = animal && animal.name;
    if (!name) {
        return 'no name dog';
    }
    return name;
}
const name = getName(namelessDog);
console.log(name); //no name dog

-> Make it shorter using the || operator

const namelessDog = {
    name: '';
};

function getName(animal) {
    const name = animal && animal.name;
    return name || 'no name dog'; //if name is falsy, use 'no name dog'
}
const name = getName(namelessDog);
console.log(name); //no name dog

Ex03. Sample code : Calculate Circle Area

function calculateCircleArea(r) {
    return Math.PI * r * r; //Math.PI is π
}
const area = calculateCircleArea(4); // If there's no parameter here, console.log(area); will be NaN
console.log(area); // 50.26548245

-> If there's no parameter, set r=1

(ES5 ver.)

function calculateCircleArea(r) {
    const radius = r || 1; //If there's no r, set radius=1
    return Math.PI * radius * radius;
}
const area = calculateCircleArea();
console.log(area); // 3.141592

(ES6 ver.)

function calculateCircleArea(r = 1) { //set r = 1 first
    return Math.PI * r * r;
}
const area = calculateCircleArea();
console.log(area); // 3.141592

(Arrow function ver.)

const calculateCircleArea = (r = 1) => Math.PI * r * r;

const area = calculateCircleArea();
console.log(area); // 3.141592

cf. https://learnjs.vlpt.us/useful/03-short-circuiting.html