Multiple ways to write?


#1

I was taught Javascript a few years ago, and I started the codecademy course in order to refresh my skills. However, I noticed some differences in the way it is taught here.

First of all, I was taught to use var. For instance, to create the variable gophersFound and set it equal to 0:

var gophersFound = 0

But codecademy seems to use:

let gophersFound = 0

Also, I was taught to check if two things are equal like this:

var gophersFound = 0
if (gophersFound == 0){
console.log("Go for the gopher!");
}

But codecademy uses three equal signs, like this:

var gophersFound = 0
if (gophersFound === 0){
console.log("Go for the gopher!");
}

What’s the difference?


#2

this is true for es5, and codecademy still has a course teaching es5:

https://www.codecademy.com/learn/learn-javascript

let was introduced in es6, which was released in 2015.

they work quite differently, var for starters has a functional scope where as let has a block scope:

if (true){
    let blockScope = "block scope"
    var functionScope = "function scope"
}

console.log(blockScope); // undefined, maybe even an error
console.log(functionScope); //  logs "function scope"

blockScope variable is defined within if clause/block, as such, it only exists within if clause/block

besides let, const was introduced which creates a constant variable (yes, a variable can be constant), this variable can’t be re-assigned:

const example = "i can't be re-assigned"
example = "would throw an error"

const also has block scope, but unlike let can’t be re-assigned

we can still use var when we need it in es6, its not that is prohibited. But you would have to defend why you would use var over let or const when working with es6.

again, massive difference:

if ("0" == 0){
    console.log(true);
}

this code will actually log true to the console, given two equal signs doesn’t compare data type, they are both zero, so this condition is true

while if ("0" === 0) is false, they are both zero, but the data type doesn’t match

three/triple equal sign is preferable in most cases


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.