Data Types

JavaScript Data Types

JavaScript has a number of different data types. The most common data types are:

  • Number
  • String
  • Boolean
  • Null
  • Undefined

The Number data type is used to store numbers. The String data type is used to store text. The Boolean data type is used to store logical values (true or false). The Null data type is used to represent a value that does not exist. The Undefined data type is used to represent a variable that has not been assigned a value.

Here is an example of how to use the different data types in JavaScript:

var x = 10; // Number
var y = "Hello, world!"; // String
var z = true; // Boolean
var w = null; // Null
var v = undefined; // Undefined

JavaScript Data Type Conversions

JavaScript automatically converts data types as needed. For example, if you try to add a number and a string, JavaScript will automatically convert the string to a number before performing the addition.

Here is an example of JavaScript data type conversions:

To convert to a string

let num = 42;
let strNum = num.toString();
console.log(typeof strNum);

To convert to a number

let str = "123";
let numStr = parseInt(str);
console.log(typeof numStr);

To convert to a boolean

let value = "true";
let boolValue = (value === "true");
console.log(typeof boolValue);

Task

Try to run the above-given code snippets to convert to a string, number, and a boolean one by one. Experiment with the code to get used to it.


		

JavaScript Data Type Summary

Here is a summary of the JavaScript variables and data types that were covered in this chapter:

  • Variables are named locations in memory that can store a value.
  • JavaScript has a number of different data types, including Number, String, Boolean, Null, and Undefined.
  • The scope of a variable determines where the variable can be used in the program.
  • JavaScript automatically converts data types as needed.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT