DEV Community

Cover image for JSP 1 : Variables, Data Types, Operators
Sophie Muchiri
Sophie Muchiri

Posted on

JSP 1 : Variables, Data Types, Operators

Introduction
JavaScript (JS) is a high-level, interpreted programming language mostly used as a client-side scripting language

It allows Developers to create interactive and dynamic webpages by manipulating the Document Object Model (DOM)
which we shall discuss later.

VARIABLES

A variable is a container in which we can store values/data.

Terms:

1. Variable declaration
This is the process of defining a new variable using a keyword (var, let)

Image description

2. Variable Initialization

This is the process of assigning an initial value to a variable after it has been declared

Image description

3. Variable assignment

Is the act of giving a variable a specific value

Image description

4. Variable look up expression
The process of accessing a value of a variable by its name within the code
(eg: using a console.log to print the value of the variable within the console)


let greeting = "Hello, World!";
console.log(greeting); 

Hello, World!
Enter fullscreen mode Exit fullscreen mode

KEY WORDS

1. var (Old Way of Declaring Variables)
✅ Can be changed (reassigned)
✅ Can be declared again (redeclared)
❌ Works in function scope (not block scope)
❌ Has hoisting issues (explained below)

NOTE WE'LL COVER SCOPE & HOISTING BETTER LATER ON

var name = "Alice";
var name = "Bob"; // ✅ No error (but can be confusing)
console.log(name); // Output: Bob

Enter fullscreen mode Exit fullscreen mode

Hoisting issues:

console.log(x); // Output: undefined (NOT an error but still 
                                                  confusing!)
var x = 10;

Enter fullscreen mode Exit fullscreen mode

2. let (The Better Way)

✅ Can be changed (reassigned)
✅ Works in block scope (inside {})
✅ Fixes the hoisting issue
❌ Cannot be declared again in the same scope

let age = 25;
age = 30;  // ✅ Allowed (Reassignment)
console.log(age); // Output: 30
let city = "Nairobi"
let city = "Mombasa" // ❌ ERROR: Cannot redeclare 'city'
Enter fullscreen mode Exit fullscreen mode

3. const (The Best Choice for Fixed Values)
✅ Cannot be changed (reassigned)
✅ Cannot be declared again
✅ Works in block scope
❌ Must be initialized when declared


const PI = 3.1415
PI = 3.14 // ❌ ERROR: Cannot reassign a 'const' variable
console.log(PI); // Output: 3.1415

Enter fullscreen mode Exit fullscreen mode

TABULAR SUMMARY

Image description

Top comments (0)