Web Development /JavaScript Programming / Lesson
Web Development

JavaScript Variables, Data Types and Type Conversion

Learn how JavaScript stores and manages information using variables, understand the major data types, and discover how to convert values from one type to another.

🎯

Learning Objectives

  • Understand how variables store data in JavaScript.
  • Use let and const correctly.
  • Understand variable scope and reassignment.
  • Identify common JavaScript primitive data types.
  • Understand strings, numbers, booleans, undefined and null.
  • Use the typeof operator.
  • Understand arrays and objects as reference data structures.
  • Perform explicit type conversion.
  • Understand implicit type coercion.
  • Write cleaner and more predictable JavaScript code.
📖

Lesson Content

Introduction

Every interactive website needs to store and process information. A student dashboard may store a student’s name, completed lessons, course progress and account status. An online shop may store product prices, quantities and customer information.

JavaScript uses variables to store information and data types to describe the kind of information being stored.

In this lesson, you will learn how to create variables, understand the major JavaScript data types and convert values from one type to another.

What Is a Variable?

A variable is a named container used to store a value.

let studentName = "David";

In this example:

  • let declares the variable.
  • studentName is the variable name.
  • "David" is the stored value.

The variable can later be used in other parts of the program.

console.log(studentName);

Declaring Variables with let

Use let when the value stored in a variable may change later.

let completedLessons = 3;

completedLessons = 4;

console.log(completedLessons);

The value changes from 3 to 4.

Declaring Variables with const

Use const when the variable should not be reassigned to another value.

const courseName = "Web Development";

console.log(courseName);

The following would cause an error:

const courseName = "Web Development";

courseName = "Data Analysis";

A good general practice is to use const by default and use let only when you know the value needs to change.

Understanding Reassignment

A variable declared with let can be reassigned.

let score = 50;

score = 80;

console.log(score);

A variable declared with const cannot be reassigned.

const school = "Dwallnet Academy";

Variable Naming Rules

JavaScript variable names must follow certain rules.

  • Names can contain letters, numbers, underscores and dollar signs.
  • Names cannot begin with a number.
  • Names cannot contain spaces.
  • JavaScript is case-sensitive.
  • Reserved JavaScript keywords should not be used as variable names.

Valid examples:

let studentName = "Ada";
let studentAge = 20;
let totalPrice = 1500;
let _courseLevel = "Beginner";

Invalid examples:

let 1student = "John";
let student name = "John";

Camel Case Naming Convention

JavaScript developers commonly use camelCase for variable names.

let studentName = "Grace";
let completedLessons = 10;
let courseProgress = 75;

The first word begins with a lowercase letter, while each additional word begins with an uppercase letter.

JavaScript Data Types

A data type describes the kind of value stored in a variable.

Some of the most important JavaScript data types are:

  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • Object
  • Array

Strings

A string represents text.

const studentName = "Dwallnet Student";

Strings can use single or double quotation marks.

const firstName = "John";

const lastName = 'Doe';

Modern JavaScript also supports template literals using backticks.

const name = "David";

const message = `Welcome, ${name}!`;

console.log(message);

Numbers

The Number data type represents numeric values.

const age = 20;

const courseFee = 150000;

const score = 87.5;

JavaScript uses the same general Number type for whole numbers and decimal numbers.

Booleans

A Boolean represents one of two values:

  • true
  • false
const isLoggedIn = true;

const isAdmin = false;

Boolean values are important when creating conditions and controlling program behaviour.

Undefined

A variable that has been declared but has not received a value is usually undefined.

let studentCourse;

console.log(studentCourse);

The output is:

undefined

Null

The value null represents an intentional absence of a value.

let selectedCourse = null;

Later, the program can assign a real value.

selectedCourse = "Web Development";

Using typeof

JavaScript provides the typeof operator for checking the type of a value.

console.log(typeof "Hello");

console.log(typeof 25);

console.log(typeof true);

The output will identify the type of each value.

Objects

Objects allow developers to group related information together.

const student = {

	name: "Ada",

	age: 21,

	course: "Web Development",

	isActive: true

};

The object contains several related properties.

Individual values can be accessed using dot notation.

console.log(student.name);

console.log(student.course);

Arrays

An array is an ordered collection of values.

const courses = [

	"Web Development",

	"Data Analysis",

	"Cyber Security",

	"Python Programming"

];

Array values can be accessed using an index.

console.log(courses[0]);

console.log(courses[1]);

Array indexing begins at zero.

Primitive and Reference Values

JavaScript values are commonly discussed as primitive values and reference values.

Primitive Values

  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • BigInt
  • Symbol

Reference Values

Objects and arrays are commonly handled as reference values.

const student = {
	name: "Grace"
};

const anotherStudent = student;

anotherStudent.name = "David";

console.log(student.name);

Understanding this behaviour becomes increasingly important when working with objects and arrays.

Explicit Type Conversion

Type conversion means changing a value from one data type to another.

JavaScript provides several built-in functions for explicit conversion.

Converting to a Number

const ageText = "25";

const age = Number(ageText);

console.log(age);

console.log(typeof age);

Using parseInt()

The parseInt() function can convert a value into an integer.

const quantity = "10";

const numberQuantity = parseInt(quantity, 10);

console.log(numberQuantity);

Using parseFloat()

Use parseFloat() when working with decimal values.

const price = "99.50";

const numberPrice = parseFloat(price);

console.log(numberPrice);

Converting to a String

The String() function converts a value into text.

const score = 90;

const scoreText = String(score);

console.log(scoreText);

console.log(typeof scoreText);

Converting to a Boolean

The Boolean() function converts a value into a Boolean.

console.log(Boolean(1));

console.log(Boolean(0));

console.log(Boolean("Hello"));

console.log(Boolean(""));

Truthy and Falsy Values

Some values behave like true or false when JavaScript evaluates them in a condition.

Common falsy values include:

  • false
  • 0
  • ""
  • null
  • undefined
  • NaN

Many other values are treated as truthy.

Implicit Type Coercion

JavaScript can sometimes automatically convert values when performing an operation. This is called implicit type coercion.

console.log("5" + 2);

This can produce:

"52"

However:

console.log("5" - 2);

JavaScript may convert the string into a number for the subtraction operation.

Because automatic conversions can sometimes create unexpected results, developers should understand the data they are working with and perform explicit conversions when necessary.

Checking for NaN

NaN means “Not a Number”.

const result = Number("Dwallnet");

console.log(result);

You can use Number.isNaN() to check whether a value is NaN.

console.log(
	Number.isNaN(result)
);

Practical Example

The following example demonstrates variables, multiple data types and type conversion.

const studentName = "John";

let completedLessons = "5";

const courseFee = 150000;

const isStudent = true;


completedLessons = Number(
	completedLessons
);


console.log(studentName);

console.log(completedLessons);

console.log(courseFee);

console.log(isStudent);

Developer Exercise

Create variables representing the following information:

  1. Your full name.
  2. Your age.
  3. Your course.
  4. Your current learning status.
  5. The number of lessons you have completed.

Then use typeof to check the data type of each value.

Mini Challenge

Examine the following code:

const price = "5000";

const quantity = 3;

const total = price * quantity;

console.log(total);

Answer the following questions:

  1. What is the original data type of price?
  2. What is the data type of quantity?
  3. What value will JavaScript produce for total?
  4. Rewrite the code using explicit type conversion.

Conclusion

Variables allow JavaScript programs to store and manage information. Data types help JavaScript understand what kind of information is being processed.

You have learned how to use let and const, work with strings, numbers and booleans, understand undefined and null, use arrays and objects, and convert values between different data types.

These concepts are essential for writing JavaScript programs. The next lessons will build on this foundation by introducing operators, conditions and decision-making in JavaScript.

💡

Practical Example

Introduction

Every interactive website needs to store and process information. A student dashboard may store a student's name, completed lessons, course progress and account status. An online shop may store product prices, quantities and customer information.

JavaScript uses variables to store information and data types to describe the kind of information being stored.

In this lesson, you will learn how to create variables, understand the major JavaScript data types and convert values from one type to another.

What Is a Variable?

A variable is a named container used to store a value.

let studentName = "David";

In this example:

  • let declares the variable.
  • studentName is the variable name.
  • "David" is the stored value.

The variable can later be used in other parts of the program.

console.log(studentName);

Declaring Variables with let

Use let when the value stored in a variable may change later.

let completedLessons = 3;

completedLessons = 4;

console.log(completedLessons);

The value changes from 3 to 4.

Declaring Variables with const

Use const when the variable should not be reassigned to another value.

const courseName = "Web Development";

console.log(courseName);

The following would cause an error:

const courseName = "Web Development";

courseName = "Data Analysis";

A good general practice is to use const by default and use let only when you know the value needs to change.

Understanding Reassignment

A variable declared with let can be reassigned.

let score = 50;

score = 80;

console.log(score);

A variable declared with const cannot be reassigned.

const school = "Dwallnet Academy";

Variable Naming Rules

JavaScript variable names must follow certain rules.

  • Names can contain letters, numbers, underscores and dollar signs.
  • Names cannot begin with a number.
  • Names cannot contain spaces.
  • JavaScript is case-sensitive.
  • Reserved JavaScript keywords should not be used as variable names.

Valid examples:

let studentName = "Ada";
let studentAge = 20;
let totalPrice = 1500;
let _courseLevel = "Beginner";

Invalid examples:

let 1student = "John";
let student name = "John";

Camel Case Naming Convention

JavaScript developers commonly use camelCase for variable names.

let studentName = "Grace";
let completedLessons = 10;
let courseProgress = 75;

The first word begins with a lowercase letter, while each additional word begins with an uppercase letter.

JavaScript Data Types

A data type describes the kind of value stored in a variable.

Some of the most important JavaScript data types are:

  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • Object
  • Array

Strings

A string represents text.

const studentName = "Dwallnet Student";

Strings can use single or double quotation marks.

const firstName = "John";

const lastName = 'Doe';

Modern JavaScript also supports template literals using backticks.

const name = "David";

const message = `Welcome, ${name}!`;

console.log(message);

Numbers

The Number data type represents numeric values.

const age = 20;

const courseFee = 150000;

const score = 87.5;

JavaScript uses the same general Number type for whole numbers and decimal numbers.

Booleans

A Boolean represents one of two values:

  • true
  • false
const isLoggedIn = true;

const isAdmin = false;

Boolean values are important when creating conditions and controlling program behaviour.

Undefined

A variable that has been declared but has not received a value is usually undefined.

let studentCourse;

console.log(studentCourse);

The output is:

undefined

Null

The value null represents an intentional absence of a value.

let selectedCourse = null;

Later, the program can assign a real value.

selectedCourse = "Web Development";

Using typeof

JavaScript provides the typeof operator for checking the type of a value.

console.log(typeof "Hello");

console.log(typeof 25);

console.log(typeof true);

The output will identify the type of each value.

Objects

Objects allow developers to group related information together.

const student = {

	name: "Ada",

	age: 21,

	course: "Web Development",

	isActive: true

};

The object contains several related properties.

Individual values can be accessed using dot notation.

console.log(student.name);

console.log(student.course);

Arrays

An array is an ordered collection of values.

const courses = [

	"Web Development",

	"Data Analysis",

	"Cyber Security",

	"Python Programming"

];

Array values can be accessed using an index.

console.log(courses[0]);

console.log(courses[1]);

Array indexing begins at zero.

Primitive and Reference Values

JavaScript values are commonly discussed as primitive values and reference values.

Primitive Values

  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • BigInt
  • Symbol

Reference Values

Objects and arrays are commonly handled as reference values.

const student = {
	name: "Grace"
};

const anotherStudent = student;

anotherStudent.name = "David";

console.log(student.name);

Understanding this behaviour becomes increasingly important when working with objects and arrays.

Explicit Type Conversion

Type conversion means changing a value from one data type to another.

JavaScript provides several built-in functions for explicit conversion.

Converting to a Number

const ageText = "25";

const age = Number(ageText);

console.log(age);

console.log(typeof age);

Using parseInt()

The parseInt() function can convert a value into an integer.

const quantity = "10";

const numberQuantity = parseInt(quantity, 10);

console.log(numberQuantity);

Using parseFloat()

Use parseFloat() when working with decimal values.

const price = "99.50";

const numberPrice = parseFloat(price);

console.log(numberPrice);

Converting to a String

The String() function converts a value into text.

const score = 90;

const scoreText = String(score);

console.log(scoreText);

console.log(typeof scoreText);

Converting to a Boolean

The Boolean() function converts a value into a Boolean.

console.log(Boolean(1));

console.log(Boolean(0));

console.log(Boolean("Hello"));

console.log(Boolean(""));

Truthy and Falsy Values

Some values behave like true or false when JavaScript evaluates them in a condition.

Common falsy values include:

  • false
  • 0
  • ""
  • null
  • undefined
  • NaN

Many other values are treated as truthy.

Implicit Type Coercion

JavaScript can sometimes automatically convert values when performing an operation. This is called implicit type coercion.

console.log("5" + 2);

This can produce:

"52"

However:

console.log("5" - 2);

JavaScript may convert the string into a number for the subtraction operation.

Because automatic conversions can sometimes create unexpected results, developers should understand the data they are working with and perform explicit conversions when necessary.

Checking for NaN

NaN means "Not a Number".

const result = Number("Dwallnet");

console.log(result);

You can use Number.isNaN() to check whether a value is NaN.

console.log(
	Number.isNaN(result)
);

Practical Example

The following example demonstrates variables, multiple data types and type conversion.

const studentName = "John";

let completedLessons = "5";

const courseFee = 150000;

const isStudent = true;


completedLessons = Number(
	completedLessons
);


console.log(studentName);

console.log(completedLessons);

console.log(courseFee);

console.log(isStudent);

Developer Exercise

Create variables representing the following information:

  1. Your full name.
  2. Your age.
  3. Your course.
  4. Your current learning status.
  5. The number of lessons you have completed.

Then use typeof to check the data type of each value.

Mini Challenge

Examine the following code:

const price = "5000";

const quantity = 3;

const total = price * quantity;

console.log(total);

Answer the following questions:

  1. What is the original data type of price?
  2. What is the data type of quantity?
  3. What value will JavaScript produce for total?
  4. Rewrite the code using explicit type conversion.

Conclusion

Variables allow JavaScript programs to store and manage information. Data types help JavaScript understand what kind of information is being processed.

You have learned how to use let and const, work with strings, numbers and booleans, understand undefined and null, use arrays and objects, and convert values between different data types.

These concepts are essential for writing JavaScript programs. The next lessons will build on this foundation by introducing operators, conditions and decision-making in JavaScript.

💻

Code Example

const studentName = "Dwallnet Student";

let completedLessons = "5";

const courseFee = "150000";

const isActive = true;


/*
|--------------------------------------------------------------------------
| Convert String Values
|--------------------------------------------------------------------------
*/

completedLessons = Number(
	completedLessons
);

const numericCourseFee = Number(
	courseFee
);


/*
|--------------------------------------------------------------------------
| Display Values
|--------------------------------------------------------------------------
*/

console.log(
	"Student:",
	studentName
);

console.log(
	"Completed Lessons:",
	completedLessons
);

console.log(
	"Course Fee:",
	numericCourseFee
);

console.log(
	"Active Student:",
	isActive
);


/*
|--------------------------------------------------------------------------
| Check Data Types
|--------------------------------------------------------------------------
*/

console.log(
	typeof studentName
);

console.log(
	typeof completedLessons
);

console.log(
	typeof numericCourseFee
);

console.log(
	typeof isActive
);
⭐

Key Takeaways

  • Variables store information that JavaScript programs can use.
  • Use const for values that should not be reassigned.
  • Use let for values that may change.
  • JavaScript supports strings, numbers, booleans, undefined, null, objects and arrays.
  • The typeof operator helps identify a value’s data type.
  • Arrays store ordered collections of values.
  • Objects group related information together.
  • Type conversion changes a value from one data type to another.
  • Number(), String() and Boolean() are useful conversion tools.
  • JavaScript can perform implicit type coercion, which developers should understand carefully.

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress