JavaScritp Types

JavaScritp Types

Describe JavaScript data types, constants and variables.

ยท

17 min read

Data refers to the values or information that is processed by a computer program. In computer science, data types refer to the various types of data that can be used in programming languages, each with its own unique characteristics and the operations that can be performed on it.

In JavaScript, examples of data types include numbers, strings, booleans, null, and undefined. The typeof operator is used to determine the data type of a variable. It is important to use the appropriate data type for a particular variable or value, as errors can arise if improper data types are used.

JavaScript also has the ability to declare constants, which are variables that cannot be reassigned once initialized. This helps ensure that certain values do not change, which can prevent errors. The const keyword is used to declare a constant, while let is used for variables that can be reassigned.

In summary, data types are an essential part of computer science and programming languages. In JavaScript, proper use of data types can help prevent errors, and the ability to declare constants further ensures proper management of data.


Importance

The importance of data types is that they determine the kind of data that can be handled by a program, as well as the way in which that data is stored and the operations that can be performed on it. This allows for more efficient use and management of memory, and can also help prevent errors that could arise from improper data types. The typeof operator in JavaScript is used to find out the data type of a particular variable.

Disadvantages

As for the disadvantages of JavaScript, one major drawback is its lack of strong typing, which can lead to errors that are difficult to debug. Additionally, JavaScript can be slow due to its interpreted nature, especially in comparison to compiled languages. However, JavaScript has become very popular with the advent of Node.js and its use in web development because of its flexibility and ubiquity.

Constants

In JavaScript, the const keyword is used to declare a constant, which is a variable that cannot be reassigned once initialized, while the let keyword is used for variables that can be reassigned. This provides a way to ensure that certain values do not change, which can help prevent bugs in the code. However, it is important to note that const does not necessarily mean that the contents of a variable cannot be changed, as is the case with objects.

Example of declaring a constant:

const PI = 3.14159265358979323846;

Example of declaring a variable that can be reassigned:

let count = 10;
count = 20;

Variables

JavaScript is a dynamically typed language, which means that the type of a variable can change at runtime. There are six primitive data types in JavaScript:

  • Number: Used for numeric values, including integers and floating-point numbers. For example:
let a = 42; // integer
let b = 3.14; // floating-point number
  • String: Used for textual data. For example:
let name = "John Doe";
  • Boolean: Used for logical values, which can be either true or false. For example:
let x = true;
let y = false;
  • Null: Represents a deliberate non-value. For example:
let z = null;
  • Undefined: Represents uninitialized variables or missing property values. For example:
let a;
console.log(a); // undefined
  • Symbol: A new data type added in ES6 used for creating unique identifiers. For example:
let id1 = Symbol("id");
let id2 = Symbol("id");
console.log(id1 === id2); // false

Besides these primitive data types, JavaScript has a reference data type called Object, which can contain key-value pairs, and functions. For example:

let person = {
  name: "John",
  age: 30,
  sayHello: function() {
    console.log("Hello!");
  }
};
console.log(person.name); // John
person.sayHello(); // Hello!

Note: In JavaScript, variables do not have to be declared with a particular data type, as the type can change based on the value assigned to it.


Falsy Values

In JavaScript, there are certain values that are considered falsy, meaning that they are treated as false when evaluated in a boolean context. These values are false, undefined, null, 0, NaN, and empty string "".

Here are some examples:

let myVar;

if (myVar) {
  console.log("This won't be printed");
} else {
  console.log("myVar is falsy");
}

let num = 0;

if (num) {
  console.log("This won't be printed");
} else {
  console.log("num is falsy");
}

let emptyString = "";

if (emptyString) {
  console.log("This won't be printed");
} else {
  console.log("emptyString is falsy");
}

In the first example, myVar is undefined, which is a falsy value, so the else block will be executed.

In the second example, num has a value of 0, which is a falsy value, so the else block will be executed.

In the third example, emptyString is an empty string, which is a falsy value, so the else block will be executed.

It's important to understand falsy values in JavaScript because they can lead to unexpected behavior if not properly accounted for in conditional statements.


Expressions

In programming, expressions are pieces of code that evaluate to a value. They can be composed of variables, operators, and function calls. Expressions can be simple, such as a single variable, or complex, such as a function call with multiple arguments.

Here are 3 propositions about expressions:

  1. Expressions can be assigned to variables, making them reusable throughout your code. For example:
const x = 4;
const y = 2;
const z = x + y; // z will have a value of 6

In the above example, we assign the result of an expression to a variable named z. We use the + operator to add the values of x and y together.

  1. Expressions can be used as part of conditional statements, to test whether a condition is true or false. For example:
if (x === y) {
  console.log("x and y are equal");
} else {
  console.log("x and y are not equal");
}

In the above example, we use the === operator to compare the values of x and y. If they are equal, the first block of code will execute, and if they are not equal, the second block of code will execute.

  1. Expressions can be combined to form more complex expressions, using operators such as && (logical AND) and || (logical OR). For example:
const a = 4;
const b = 2;
const c = 7;

if (a > b && c > a) {
  console.log("a is greater than b and c is greater than a");
} else {
  console.log("this condition is not met");
}

In the above example, we combine two expressions using the && operator. The first expression (a > b) checks whether a is greater than b, and the second expression (c > a) checks whether c is greater than a. If both expressions are true, then the code inside the first block will execute.

Overall, expressions are a fundamental concept in programming, and understanding how to create and use them is critical to writing effective code.


Numeric Expressions

Numeric expressions in JavaScript are used to perform mathematical calculations with numbers. JavaScript supports basic arithmetic operations such as addition, subtraction, multiplication, and division, as well as more complex operations such as exponentiation, modulus, and increment/decrement.

Here are some examples of numeric expressions in JavaScript:

let a = 10;
let b = 5;

let sum = a + b; // 15
let difference = a - b; // 5
let product = a * b; // 50
let quotient = a / b; // 2
let remainder = a % b; // 0

let exponentiation = a ** 2; // 100

a++; // a is now 11
b--; // b is now 4

In the above example, we define two variables a and b and use them in various numeric expressions. We also use a++ and b-- to increment and decrement the values of a and b, respectively.

Overall, numeric expressions are a fundamental part of JavaScript and are used extensively in programming to perform mathematical calculations, manipulate numbers, and solve complex problems.


Bitwise Expressions

Bitwise expressions in JavaScript are used to perform operations on the bit-level of binary numbers. These operations can be used for various purposes such as cryptography, compression, and data analysis. Bitwise operators can be applied to integers, but they first convert the integers to 32-bit binary format, perform the operation, and then return the result.

Here are some examples of bitwise expressions in JavaScript:

let a = 5; // 00000000000000000000000000000101
let b = 3; // 00000000000000000000000000000011

let and = a & b; // 00000000000000000000000000000001
let or = a | b; // 00000000000000000000000000000111
let xor = a ^ b; // 00000000000000000000000000000110
let not = ~a; // 11111111111111111111111111111010
let leftShift = a << 1; // 00000000000000000000000000001010
let rightShift = a >> 1; // 00000000000000000000000000000010
let zeroFillRightShift = a >>> 1; // 00000000000000000000000000000010

In the above example, we define two variables a and b and use them in various bitwise expressions. We use & for bitwise AND, | for bitwise OR, ^ for bitwise XOR, ~ for bitwise NOT, << for left shift, >> for right shift, and >>> for zero-fill right shift.

Overall, bitwise expressions are not used very often in JavaScript, but they are an important concept to understand for certain programming applications.


Use-Cases

Bitwise operators are useful when performing operations at the bit level, and can be used to improve the efficiency or performance of certain critical functions. Here are some interesting use cases:

  1. Setting or unsetting individual bits in an integer: The bitwise OR operator can be used to set a specific bit to 1, and the bitwise AND operator can be used to unset a specific bit. This can be useful in situations where we want to toggle a single flag or bit in a given variable.
// set the third bit to 1
const flags = 0b0100;
const newFlags = flags | 0b1000; // newFlags will be 0b1100

// unset the second bit
const num = 0b1010;
const clearedNum = num & ~0b0100; // clearedNum will be 0b1000
  1. Checking whether a number is even or odd: The least significant bit of an integer is set to 0 if the number is even and 1 if the number is odd. By using the bitwise AND operator with 1, we can quickly determine whether a number is even or odd.
function isEven(num) {
  return (num & 1) === 0;
}

console.log(isEven(4)); // true
console.log(isEven(5)); // false
  1. Converting RGB values to hexadecimal: In web development, we often need to convert RGB values (red, green, blue) to hexadecimal values for use in CSS. This can be done using bitwise operators to shift the individual color values by 8 bits and then combine them using the bitwise OR operator.
function rgbToHex(red, green, blue) {
  return ((red << 16) | (green << 8) | blue).toString(16).padStart(6, '0');
}

console.log(rgbToHex(255, 0, 255)); // "ff00ff"

Overall, bitwise operators can be used in a variety of interesting ways to optimize performance and improve code efficiency in certain critical functions.


String Expressions

String expressions are a way to include strings and JavaScript expressions in template literals, which are enclosed in backticks () in JavaScript. A template literal can include placeholders ${}that can be used to embed JavaScript expressions that will be evaluated and concatenated into the final string. For example, you can define a string variablesongand two numerical variablesscoreandhighestScore`, and use them to create a template literal:

const song = "Fight the Youth";
const score = 9;
const highestScore = 10;
const output = `I like the song ${song}. I gave it a score of ${
  (score / highestScore) * 100
}%.`;
console.log(output); // "I like the song Fight the Youth. I gave it a score of 90%."

In this example, the ${song} placeholder is replaced with the string value of song, and the ${(score/highestScore)*100} placeholder is replaced with the percentage calculated from score and highestScore, which is then evaluated and concatenated with the surrounding string.

In addition to being able to include expressions, template literals also preserve line breaks and formatting from the source code. This makes it possible to define multiline strings without using escape characters or concatenation:

const output = `I like the song.
I gave it a score of 90%.`;
console.log(output);

/*
I like the song.
I gave it a score of 90%.
*/

There are several advanced features of template literals, like tagged templates and raw string access, that allow for even more flexibility in string manipulation. You can learn more about them from the Template literals reference page.


Logic Expressions

Logic expressions in JavaScript are expressions that evaluate to either true or false. They are typically used in conditional statements (such as if-else), loops, and other control flows to decide what actions should be taken next. Logic expressions are created using relational operators, which are operators that compare two values and return either true or false. The most common relational operators in JavaScript are:

  • > greater than

  • < less than

  • >= greater than or equal to

  • <= less than or equal to

  • == equal to (loose equality test)

  • === equal to (strict equality test)

  • !== not equal to (strict inequality test)

  • != not equal to (loose inequality test)

For example:

const x = 5;
const y = 10;

if (x < y) {
  console.log("x is less than y");
} else {
  console.log("x is greater than or equal to y");
}

In this example, we're using the less than (<)operator to compare x and y, and the resulting boolean value determines which branch of the if...else statement is executed.

Ternary Expression

The ternary operator, also known as the conditional operator in JavaScript, is a shorthand way of writing an if-else statement. It allows you to test a condition and return a value if the condition is true, and another value if the condition is false. It is useful when you have two alternatives or choices that are selected based on a true/false condition, and it can save space and make your code more readable.

Here is a syntax example of a ternary operator:

condition ? expression1 : expression2;

The condition is the test expression that will return a boolean value (true or false). If the condition is true, the expression1 will be executed, otherwise, expression2 will be executed. Here is an example code that demonstrates the ternary operator in action:

const age = 18;
const canVote = age >= 18 ? "You can vote" : "You cannot vote";
console.log(canVote); // Output: "You can vote"

In this example, we initialized the age variable with a value of 18 and created a canVote variable that stores the result of the ternary operator. The ternary operator tests if the age is greater than or equal to 18. If it is, it returns the string 'You can vote', otherwise, it returns the string 'You cannot vote', which gets assigned to the canVote variable. The console then logs the value of the canVote variable, which outputs "You can vote".

In summary, the ternary operator is a shorthand way of writing an if-else statement in JavaScript. It is useful when you want to assign a value to a variable based on a true/false condition, and it can help make your code more readable and concise.

Boolean Expressions

Boolean expressions are expressions that evaluate to either true or false, but unlike logic expressions they are not used to make decisions. Instead they are used as conditions themselves, or to express the truth value of an expression. For example:

const a = 10;
const b = 20;

const result = a > b; // false

if (result) {
  console.log("The condition is true");
} else {
  console.log("The condition is false");
}

In this example, we're storing the result of the a > b comparison in a variable called result, and then using that variable as the condition for an if...else statement.

Overall, while there is some overlap between logic expressions and boolean expressions, the key difference is that logic expression are used to make decisions, while boolean expressions are used to express the truth value of an expression.


Coercion & Conversion

Data coercion in JavaScript is the automatic type conversion of data from one type to another when operands of differing types are involved in a binary (two-term) operation. For example, if a number is added to a string, JavaScript will convert the number to a string and concatenate the two strings. This can often lead to unexpected behavior, so it's important to be aware of how coercion works.

On the other hand, data conversion refers to the intentional transformation of data from one type to another. There are multiple ways to achieve data conversion, and a few common examples include:

  • Using the Number() function to convert a string to a number, if possible.
const myString = "123";
const myNum = Number(myString);
console.log(typeof myNum); // number
  • Using the toString() method to convert a number to a string.
const myNum2 = 123;
const myString2 = myNum2.toString();
console.log(typeof myString2); // string

When it comes to conversion between strings and numbers, it's important to remember that JavaScript automatically coerces values to a common type when they are used together in an expression. When a string is concatenated with a number, the number is converted to a string.

const name = "Front ";
const number = 242;
console.log(`${name}${number}`); // "Front 242"

Conversely, when a string is compared with a number, the string is converted to a number (if possible).

const a = "10";
const b = 20;
console.log( a+b ); // "1020" (string concatenation)
console.log( +a+b ); // 30 (number addition)

In conclusion, data coercion and data conversion are two important concepts to understand in JavaScript. Coercion can sometimes result in unexpected behavior, so it's important to be aware of it when creating code. Meanwhile, data conversion is often necessary when working with different data types, and can be achieved using a variety of techniques in JavaScript.


In JavaScript, Date-Time expressions are used to work with dates and times. The Date object in JavaScript is used to represent a date and time, and there are several methods available to work with it. Here are some examples:

// creating a new Date object
const date = new Date();

// getting the current date
const year = date.getFullYear();
const month = date.getMonth();
const day = date.getDay();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
console.log(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);

// getting the timestamp of a date
const timestamp = date.getTime();
console.log(`Timestamp: ${timestamp}`);

// creating a date from a timestamp
const date2 = new Date(timestamp);
console.log(`Recreated date: ${date2}`);

// creating a date from a string
const dateString = "2022-10-31T18:30:00.000Z";
const date3 = new Date(dateString);
console.log(`Parsed date: ${date3}`);

In the code above, we create a new Date object and use various methods to get information about the current date and time, including the current year, month, day, hours, minutes, and seconds. We also show how to get the timestamp of a date using the getTime() method, and how to recreate a date object from a timestamp using new Date(timestamp). Finally, we demonstrate how to create a date object from a string using the Date constructor.

JavaScript has many more methods available for working with dates and times, so it's important to consult the documentation to see what else is possible.


Best Practice

Sure, here are some best practices for working with expressions and variables in JavaScript:

  1. Always declare your variables using let, const, or var. This helps avoid accidentally creating global variables or redefining variables.
let myVar = "hello"; // preferred way of declaring a variable
const myConst = "world"; // declare a variable that can't be reassigned
var myOldVar = "goodbye"; // avoid using var (old way of declaring a variable)
  1. Use meaningful variable names that describe what the variable is storing.
// example of bad variable names
let a = 10;
let b = 20;

// example of good variable names
let width = 10;
let height = 20;
  1. Break complex expressions into smaller, more readable parts.
// example of a complex expression
result = ((a * b) - c) * 2;

// example of a simplified expression
let intermediateResult = (a * b) - c;
result = intermediateResult * 2;
  1. Avoid using eval() to evaluate expressions, as it can be dangerous and unpredictable.
// example of using eval() (bad practice)
let x = 10;
let y = 20;
let expr = "x + y";
let result = eval(expr); // returns 30
  1. Use == or === to compare expressions, depending on whether you want to perform type coercion or not.
// example of using ==
let num1 = 10;
let num2 = "10";
console.log(num1 == num2); // true (type coercion happens)

// example of using ===
console.log(num1 === num2); // false (no type coercion happens)

By following these best practices, you can avoid common errors and write more readable and maintainable code in JavaScript.


Disclaimer: Congratulation, you have learned basic data types in JavaScript. This article was created with help from ChatGPT with my prompts. It is not a replacement for JavaScript documentation.


Learn and prosper. ๐Ÿ––

ย