Why to use var? It is working also without it


#1

<PLEASE USE THIS TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>

https://www.codecademy.com/courses/learn-javascript/lessons/variables/exercises/string-interpolation?action=lesson_resume

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>

```

These two scripts prints the same output, so why to use the “var” at the first place?

var favoriteAnimal = "dog";
console.log('My favorite animal: ' + favoriteAnimal);
favoriteAnimal = "dog";
console.log('My favorite animal: ' + favoriteAnimal);
<do not remove the three backticks above>

#2

You are correct. JavaScript lets you create a new variable without declaring it using var. But only when you are not in 'strict mode;'.

In doing so, you are creating a global variable. Globals can be lead to unexpected behavior. Therefore, it’s recommended that we always declare variables using var, let, or const.

If you turn on strict mode, you’ll see that you get a ReferenceError: favoriteAnimal is not defined error.

Typically, we write real-world apps in 'strict mode';.

Here are some references if you’d like to learn more:


Changing variables
#3

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