DEV Community

loading...
Cover image for JAVASCRIPT VARIABLES

JAVASCRIPT VARIABLES

kokoh profile image Kokoh Gift Ewerem ・2 min read

What is a variable?
A variable is a named location for storing a value. That way an unpredictable value can be accessed through a predetermined name.
Think of it as a container for storage.
When you say to yourself, “I need to remember all this information later but I only want to remember on word for all the information, that is a variable!

Variables don’t have types, but the value in them do. These types define intrinsic behavior of values. – Kyle Simpson

Javascript has seven built-in value.

  1. String- a sequence of character that represents a text value. E.g “Howdy”
  2. Number-an interger or floating point number. E.g 42
  3. Undefined- a top-level property whose value is not defined. . E.g let b; console.log(b) // undefined
  4. Boolean- a true or false statement. E.g if (Boolean conditional){ console.log(“Boolean conditional resolved to true”); } else { console.log(“Boolean conditional resolved to false”);
  5. null- a special keyword denoting a null value.
  6. Symbol- a data type whose instances are unique and immutable.
  7. Object refers to a data structure containing data and instructions for working with the data. Objects sometimes refer to real-world things, for example a car or map object in a racing game. E.g let car ={ color: “red” miles:400 }console.log(car.color) //red Note: all of these types except objects are called primitives”

There are 3 different ways to declare a variable in Javascript which are: var , let and const.

Var is an outdated way to declare variables. Before 2015 using var keyword was the only way to declare a Javascript variable. Variables declared with a var keyword is termed as a global variable as it can be accessed anywhere(globally or locally) it can be redefined. E.g
var carName = "Volvo";
var carName = Toyota; //can be redefined

Let is a block scope, it can’t be used outside a block scope. It can be updated or redefine. E.g {
let x = 2;
}
// x can NOT be used outside the above block-scope here

Const is a block scope. As the name implies, ‘constant’, once assigned, it cannot be reassigned. It does not define a constant value rather a constant reference to a value. E.g
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; //ERROR

NOTE:
Don’t use var anymore. If you’re worried about compatibility in browsers, it has 94% global compatibility.

Discussion (0)

pic
Editor guide