Function Confusion of Let and Var


#1

Hello, can someone please help explain this. I completed function and Scope exercise in which i used const and let to create variables. for example in return I and return II (5/10 and 6/10) in functions. However checking the forums , I saw other post where instead of let , there is var, are we doing the same exercise or did the exercises change? I dont understand this, because i never came across var in my function exercise .


#2

The exercises may have changed last autumn, where ES6 syntax was introduced into course.

Briefly,

var is what we used to (and still can) use to define scope. A variable declared in global scope didn’t really need the keyword since its scope is already defined, but we made a habit of using it just for good practice. Inside a function things are different. Functions define their own scope (environment) and if we declare a variable without the keyword it will end up being a global variable. This is not really a good practice since we are polluting the global namespace with variables that could collide with other parts of the program.

var number = 42;

function foo():
    number = 84;
}

console.log(number);    //  84

See how the function’s number value overwrote the global value? To prevent this we would use var inside the function. That way they are two different variables (since they are in two different scopes).

There is one tiny exception to consider… The parameter.

var number =  42;
function foo(number):
    return number;
}
console.log(number);     //  42
console.log(foo(84));    //  84

The parameter variable is defined in function scope. Again, two different scopes. The parameter is said to shadow the global variable.

var declarations are dynamic, meaning their values and type can be changed on the fly with a new assignment.

var str = "Hello";
console.log(str);    //  Hello
str = str.length;
console.log(str);    //  5

Notice that we do not use var more than once. Just reassignment.

I’ll post this now so you can read it while I muster up some more on the topic of const and let. Will edit this post in a short while.


There is one thing to add to the above, known as variable leakage.

for (var i = 0; i < 10; i++) {
    console.log(i);
}

0
1
2
3
4
5
6
7
8
9

console.log(i);    //  10

Notice that the last value of i is still in memory and permitted to leak out of the loop. This might be the effect we desire, but if we don’t, then ES6 block scope gives us a way to prevent it… let.

for (let i = 0; i < 10; i++) {
    console.log(i);
}

// same output as before

console.log(i);    // undefined

Now we see there is no leakage. i is defined in the block scope of the loop body, and is undefined outside of the block.

let variables are like var in that they are dynamic. Their value and or type can be changed on the fly.

const is what it implies… A constant. const declared variables are static and cannot be changed once declared. The only exception to this is reference objects such as arrays and objects. Their type cannot be changed but the values they contain are dynamic and can be changed in both type and value. The object length is also dynamic so we can insert or remove elements or key:value pairs.


#3

Thank you very much @mtf , its making a little sense, trying to bring in var and to see how different it is from let (at least i can see the difference between var and const), so does that mean that var and let can be used exactly the same way or interchangeably , but the only difference is that let allow no leakage and var does allow leakage out of the loop.

Because I have noticed that even though the exercise is not the same, the differences is in the (var and let) the new exercise used let at places where the old exercise used var. is that right?


#4

There really isn’t much difference between var and let other than block scope on let. They both treat function scope the same.

let number = 42;

function foo() {
    number = 84;
}

console.log(number);    //  84

#5

Thank you, that makes sense.
I was just wondering though, a person did the same function exercise yesterday but his function topic (Return I and Return II) contain var , while mine contain let. why the difference?


#6

I can only answer in the subjective without actually checking the lesson. Please post a link to the exercise. Thanks. Edit: found the lessons

Functions - return II

Here is ES5 syntax,

function takeOrder(topping, crustType) {
  orderCount++;
  console.log('Order: ' + crustType + ' pizza topped with ' + topping);
}
function getSubTotal(itemCount){
  return itemCount * 7.5;
}
function getTax() {
  return getSubTotal(orderCount) * 0.06;
}
function getTotal() {
  return getSubTotal(orderCount) + getTax();
}
var orderCount = 0;


takeOrder('bacon', 'thin crust');
takeOrder('cheese', 'thick crust');
takeOrder('anchovies', 'garlic crust');

console.log(getSubTotal(orderCount));
console.log(getTotal());
Order: thin crust pizza topped with bacon
Order: thick crust pizza topped with cheese
Order: garlic crust pizza topped with anchovies
22.5
23.85

Here is the same thing in ES6 syntax:

const takeOrder = (topping, crustType) => {
  orderCount++;
  console.log(`Order: ${crustType} pizza topped with ${topping}`);
};

const getSubTotal = itemCount => itemCount * 7.5;

const getTax = () => getSubTotal(orderCount) * 0.06;

const getTotal = () => getSubTotal(orderCount) + getTax();

let orderCount = 0;


takeOrder('bacon', 'thin crust');
takeOrder('cheese', 'thick crust');
takeOrder('anchovies', 'garlic crust');

console.log(getSubTotal(orderCount));
console.log(getTotal());

Same output.

When we can improve readability with no loss of functionality, the new syntax wins hands down. BUT, it does not matter when it comes down to it. It’s more important that we write code that works as expected than how we actually choose to compose it. var and let only concern themselves with the scope in which they are declared.


#7

Thats wonderfully explained, i got it now, Thank you.


#8

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