DEV Community

Joy Lee 🌻
Joy Lee 🌻

Posted on • Edited on

[JS] Understanding JavaScript Variables and Assignment Operators

Reference
Codecademy. Retrieved from https://www.codecademy.com/


A variable is a container for data that is stored in computer memory. It is referenced by a descriptive name that a programmer can call to assign a specific value and retrieve it.

let name = "Tammy";
const found = false;
var age = 3;
console.log(name, found, age);
// Tammy, false, 3
Enter fullscreen mode Exit fullscreen mode

To declare a variable in JavaScript, any of these three keywords can be used along with a variable name:

  • var is used in pre-ES6 versions of JavaScript.
  • let is the preferred way to declare a variable when it can be reassigned.
  • const is the preferred way to declare a variable with a constant value.

let Keyword

let creates a local variable in JavaScript & can be re-assigned. Initialization during the declaration of a let variable is optional. A let variable will contain undefined if nothing is assigned to it.

let count; 
console.log(count); // Prints: undefined
count = 10;
console.log(count); // Prints: 10
Enter fullscreen mode Exit fullscreen mode

const Keyword

A constant variable can be declared using the keyword const. It must have an assignment. Any attempt of re-assigning a const variable will result in JavaScript runtime error.

const numberOfColumns = 4;
numberOfColumns = 8;
// TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

Assignment Operators

An assignment operator assigns a value to its left operand based on the value of its right operand. Here are some of them:

  • += addition assignment
  • -= subtraction assignment
  • *= multiplication assignment
  • /= division assignment
let number = 100;

// Both statements will add 10
number = number + 10;
number += 10;

console.log(number); 
// Prints: 120
Enter fullscreen mode Exit fullscreen mode

String Interpolation

String interpolation is the process of evaluating string literals containing one or more placeholders (expressions, variables, etc).

It can be performed using template literals: text ${expression} text.

let age = 7;

// String concatenation
'Tommy is ' + age + ' years old.';

// String interpolation
`Tommy is ${age} years old.`;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)