DEV Community

Cover image for Getting Started with JavaScript: Variables and Data Types
ISHAQ HASSAN
ISHAQ HASSAN

Posted on

Getting Started with JavaScript: Variables and Data Types

Introduction

One of the foundational concepts in JavaScript is understanding how to declare and use variables, along with the different data types available. This guide is designed and written for beginners and early intermediate let's journey you through the nitty and gritty of JavaScript variables and data types, using var, let, and const declarations.

Variable: A variable is a container that stores a value that can be used in a program. Variables have a name, a data type, and a value.

Data Type: A data type is a classification of data that determines the type of value a variable can hold. Data types also determine the operations that can be performed on the data.

JavaScript variable is used to store data and can be created using var, let, and const keywords. Below is a simple javascript code of the three (3) declarations.

let myVariable = 'value'  
const myConstant = 'constant';  
var myVar = 'variable';  
Enter fullscreen mode Exit fullscreen mode

Explanation
The code demonstrates the following:

  • declares a variable with the value 'value'
  • declares a constant variable with the value 'constant'
  • declares a variable with the value 'variable'

Javascript var declaration keyword
The var keyword is the oldest keyword amongst the variable declaration keywords, it can be function-scoped or global-scoped which means it can be accessed within a function in which it is defined, and outside if defined, can be accessed by any function.

Example 1: num1 below is a global-scoped variable and num2 is a function-scoped variable that can only be accessed via the function func().

var num1 = 10
function func() {
    var num2 = 20
    console.log(num1, num2)
}
func();
console.log(num1);

Enter fullscreen mode Exit fullscreen mode

Output

10 20
10

Explanation:

  • var num1 = 10 declares a global variable num1 with the value 10.
  • function func() defines a function func that declares a local variable num2 with the value 20 and logs both num1 and num2 to the console.
  • func() calls the function, logging 10, 20 to the console.
  • console.log(num1) logs the global variable num1 to the console, resulting in 10.

The below code tries to access the function-scoped variable

console.log(num2);
Enter fullscreen mode Exit fullscreen mode

Output

ReferenceError: num2 is not defined

Explanation

  • num2 is only defined inside the scope of the func() function, so when you try to log it outside of that scope, it's undefined.

Example 2: variables can be re-declared, such as num1 and num2 in the below code were redeclared showcasing how it affects both global-scoped and function-scoped.

var num1 = 10
function func() {
    var num2 = 20
    var num2 = "ten" 
    console.log(num2)
}
func();
var num1 = 20
console.log(num1);
Enter fullscreen mode Exit fullscreen mode

Output

ten
20

Explanation

  • num1 is a global variable, defined outside the function, so it can be accessed and modified from anywhere in the code.
  • num2 is a local variable, defined inside the function, so it can only be accessed and modified within the func() function. Once the function finishes executing, num2 is no longer accessible.

JavaScript let declaration Keyword
The let declaration keyword is introduced in ECMAScript 2015(ES6). It is an improved version of the var declaration keyword. Variables declared with let uses block scope. It is not accessible outside a particular code block.

Example 1: The code below demonstrates the let var declaration

function happy() {
    let mood = "don't know"
    if (mood == "happy"){
        console.log("I'm am ",mood)
    }
    else if (mood == "sad"){
        console.log("I'm am ",mood)
    }
    else{
        console.log("I'm am ",mood)
    }
}
happy();
Enter fullscreen mode Exit fullscreen mode

Output:

I'm am don't know

Explanation

  • The code defines a function happy() that:
  • Sets a variable mood to "don't know"
  • Checks if the mood is "happy", "sad", or neither
  • Logs a message to the console with the value of mood

Example 2: The code below demonstrates let variable declaration outside the if statement's block.

function happy() {
    let mood = "jolly"
    if (mood == "happy"){
        let mood = "don't know"
        console.log("I'm am ",mood)
    }
    console.log("I'm am ", mood)

}
happy();
console.log("I'm am ", day)

happy();
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The happy() function sets mood to "jolly".
  • The if statement checks if mood is "happy", but it's not, so the code inside the if block is skipped.
  • The function logs "I'm am jolly" to the console.
  • The function is called, executing the code inside it.
  • Finally, the code tries to log the value of day, but day is not defined, so it logs undefined.

Output:

console.log("I'm am ", day)
^
ReferenceError: day is not defined

JavaScript constdeclaration Keyword
The const declaration keyword possesses all let keyword features their major difference is that const can’t be changed, it is used to assign variables that have fixed values examples such as pi, acceleration due to gravity, etc.
Example 1: The code below demonstrates the pi declaration later it was re-declared which returns an error code.

const pi =  3.14159;
function func() {
    pi = 34
    console.log(pi)
}
func();
Enter fullscreen mode Exit fullscreen mode

Output:

pi = 34
^
TypeError: Assignment to constant variable.

JavaScript consists of two types of data types which are:

  1. Primitive data types
  2. Non-primitive(complex) data types

Primitive Data Types: These are data types whose variables can hold only a single value, and are immutable (i.e. cannot be changed in memory location).
Number: These values consist of numbers, represented as floating-point numbers (e.g., 42.67, 3.14, etc.). and Special values like NaN (Not a Number), Infinity, and -Infinity.

let num1 =12
let num = 10.7
Enter fullscreen mode Exit fullscreen mode

String: A sequence of characters (e.g., "hello", 'hello'), represented as a string of Unicode characters.


javascript
• let firstName = “Bala”
• let LastName = ‘Babangida’

Boolean: A true or false value.

let isStudent = true
let isLecturer = false
Enter fullscreen mode Exit fullscreen mode

Null: A null value, representing the intentional absence of any object value.

let firstName = Bala
let LastName = Babangida
let middleName = null
Enter fullscreen mode Exit fullscreen mode

Undefined: A variable is said to be undefined if it is uninitialized (i.e it has no assign value). Below is code demonstration of undefined value.

let middleName;
let isPregnant;
let Age;
Enter fullscreen mode Exit fullscreen mode

BigInt: is are whole numbers larger than 2^53 - 1, which is the largest number JavaScript can reliably represent with the Number primitive. BigInt values are created by appending n to the end of an integer or by using the BigInt function.


let bigNumber = 1234567890123456789012345678901234567890n;
Enter fullscreen mode Exit fullscreen mode
  • Symbol: A unique identifier, used to create unique property keys (new in ECMAScript 2015).
// Create a Symbol
let mySymbol = Symbol();

// Create an object with a Symbol key
let obj = {
  [mySymbol]: "Symbol value"
};

// Access the value using the Symbol key
console.log(obj[mySymbol]); // Output: "Symbol value"

// Try to access the value with a string key
console.log(obj["mySymbol"]); // 
Enter fullscreen mode Exit fullscreen mode

Output:
undefined

Difference between null data type and undefined data types

For starter null and undefined data types mean variable values that are empty. But what distinguishes the both can best be understood using a case study, below are case study of null and undefined data types.

Case Study 1:

  • Bala creates a new account on an e-commerce platform.
  • He skips adding his age (which is an optional field) and middle name (which is not required).
  • His age is assigned a null value because it's an attribute he has (i.e., the field exists, but he chose not to fill it).
  • His middle name is assigned an undefined value because it's an attribute he lacks (i.e. the field doesn't exist or does not apply to him)

Case Study 2:

  • A developer is working on a program that retrieves a user's address from a database.
  • The database has fields for street, city, state, and zip code.
  • If a user has not provided their address, the database returns null for all address fields.
  • However, if the database doesn't have a field for a particular piece of information (e.g., fax number), it returns undefined.
  • In this case, the developer can check for null to handle missing data and undefined to handle non-existent fields.

These case studies illustrate the difference between null and undefined:

  • Null represents an empty or missing value for an existing attribute or field.
  • Undefined represents a non-existent attribute or field, or a lack of value for a particular property or variable.

Non-Primitive Data Types (Complex):
Object: A collection of key-value pairs, where keys are strings or symbols and values can be any type (e.g., {name: "John", age: 30}). Objects are changed and can also be extended or modified.
The code below demonstrates creating an object person with properties name and age, and a method greet.

// Object example
const person = {
  name: "John",
  age: 30,
  greet: function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
  }
};

person.greet(); // Output: Hello, my name is John and I am 30 years old.
Enter fullscreen mode Exit fullscreen mode

Array: A collection of values of any type, indexed by integers (e.g., [1, 2, 3], ["a", "b", "c"]). Arrays can be changed and extended or modified. The code below demonstrates creating an array of colors and accessing its elements.

// Array example
const colors = ["red", "green", "blue"];
console.log(colors[0]); 

colors.push("yellow"); // Add a new element to the array
console.log(colors); 
Enter fullscreen mode Exit fullscreen mode

Output

red
["red", "green", "blue", "yellow"]

Explanation

  • Creates an array colors with three elements: "red", "green", and "blue".
  • Logs the first element of the array (colors[0]), which is "red".
  • Adds a new element "yellow" to the end of the array using the push() method.
  • Logs the updated array, which now contains four elements: "red", "green", "blue", and "yellow".

The indexing of array starts from zero (0) up to the last index which is n-1. Where n is any number between 0 and the length of the array.

Function: A block of code that can be called with arguments, returning a value (e.g., function greet(name) { console.log("Hello, " + name); }). Functions are objects and can have properties and methods. The code example below demonstrates defining a function add that takes two arguments and returns their sum.

Example 1: Below is a code demonstration of an addition Function.

function add(x, y) {
  return x + y;
}

const result = add(2, 3);
console.log(result); // Output: 5
Enter fullscreen mode Exit fullscreen mode

Example 2: Function as an object

function greet(name) {
  console.log("Hello, " + name);
}

greet("Jane"); 

console.log(greet.name); 
console.log(typeof greet); 
Enter fullscreen mode Exit fullscreen mode

Output

Hello, Jane
greet
function

Explanation

  • Defines a function greet that takes a name and logs a greeting message.
  • Calls the function with the name "Jane", logging "Hello, Jane".
  • Logs the function's name (greet) and type (function).

Conclusion

Understanding variables and data types is crucial for effective programming in JavaScript. By using var, let, and const, you can manage the scope and mutability of your variables. Recognizing the difference between primitive and non-primitive data types helps in organizing and manipulating data efficiently. Keep practicing these concepts to become more proficient in JavaScript.

Top comments (6)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

You've omitted BigInt from the primitive data types.

Collapse
 
ishaq_360 profile image
ISHAQ HASSAN • Edited

Thank you ur observation is much appreciated

Collapse
 
brysenrom profile image
Brysen-Rom

very well explanation

Collapse
 
ishaq_360 profile image
ISHAQ HASSAN

Thank you

Collapse
 
umarshehu profile image
Umar Shehu

You did very well!

Collapse
 
ishaq_360 profile image
ISHAQ HASSAN

Thank you

Some comments may only be visible to logged-in visitors. Sign in to view all comments.