• Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

JavaScript data types and data structures

Programming languages all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in JavaScript and what properties they have. These can be used to build other data structures.

The language overview offers a similar summary of the common data types, but with more comparisons to other languages.

Dynamic and weak typing

JavaScript is a dynamic language with dynamic types . Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types:

JavaScript is also a weakly typed language, which means it allows implicit type conversion when an operation involves mismatched types, instead of throwing type errors.

Implicit coercions are very convenient, but can create subtle bugs when conversions happen where they are not expected, or where they are expected to happen in the other direction (for example, string to number instead of number to string). For symbols and BigInts , JavaScript has intentionally disallowed certain implicit type conversions.

Primitive values

All types except Object define immutable values represented directly at the lowest level of the language. We refer to values of these types as primitive values .

All primitive types, except null , can be tested by the typeof operator. typeof null returns "object" , so one has to use === null to test for null .

All primitive types, except null and undefined , have their corresponding object wrapper types, which provide useful methods for working with the primitive values. For example, the Number object provides methods like toExponential() . When a property is accessed on a primitive value, JavaScript automatically wraps the value into the corresponding wrapper object and accesses the property on the object instead. However, accessing a property on null or undefined throws a TypeError exception, which necessitates the introduction of the optional chaining operator.

Type return value Object wrapper
N/A
N/A

The object wrapper classes' reference pages contain more information about the methods and properties available for each type, as well as detailed descriptions for the semantics of the primitive types themselves.

The Null type is inhabited by exactly one value: null .

Undefined type

The Undefined type is inhabited by exactly one value: undefined .

Conceptually, undefined indicates the absence of a value , while null indicates the absence of an object (which could also make up an excuse for typeof null === "object" ). The language usually defaults to undefined when something is devoid of a value:

  • A return statement with no value ( return; ) implicitly returns undefined .
  • Accessing a nonexistent object property ( obj.iDontExist ) returns undefined .
  • A variable declaration without initialization ( let x; ) implicitly initializes the variable to undefined .
  • Many methods, such as Array.prototype.find() and Map.prototype.get() , return undefined when no element is found.

null is used much less often in the core language. The most important place is the end of the prototype chain — subsequently, methods that interact with prototypes, such as Object.getPrototypeOf() , Object.create() , etc., accept or return null instead of undefined .

null is a keyword , but undefined is a normal identifier that happens to be a global property. In practice, the difference is minor, since undefined should not be redefined or shadowed.

Boolean type

The Boolean type represents a logical entity and is inhabited by two values: true and false .

Boolean values are usually used for conditional operations, including ternary operators , if...else , while , etc.

Number type

The Number type is a double-precision 64-bit binary format IEEE 754 value . It is capable of storing positive floating-point numbers between 2 -1074 ( Number.MIN_VALUE ) and 2 1023 × (2 - 2 -52 ) ( Number.MAX_VALUE ) as well as negative floating-point numbers of the same magnitude, but it can only safely store integers in the range -(2 53 − 1) ( Number.MIN_SAFE_INTEGER ) to 2 53 − 1 ( Number.MAX_SAFE_INTEGER ). Outside this range, JavaScript can no longer safely represent integers; they will instead be represented by a double-precision floating point approximation. You can check if a number is within the range of safe integers using Number.isSafeInteger() .

Values outside the representable range are automatically converted:

  • Positive values greater than Number.MAX_VALUE are converted to +Infinity .
  • Positive values smaller than Number.MIN_VALUE are converted to +0 .
  • Negative values smaller than - Number.MAX_VALUE are converted to -Infinity .
  • Negative values greater than - Number.MIN_VALUE are converted to -0 .

+Infinity and -Infinity behave similarly to mathematical infinity, but with some slight differences; see Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY for details.

The Number type has only one value with multiple representations: 0 is represented as both -0 and +0 (where 0 is an alias for +0 ). In practice, there is almost no difference between the different representations; for example, +0 === -0 is true . However, you are able to notice this when you divide by zero:

NaN (" N ot a N umber") is a special kind of number value that's typically encountered when the result of an arithmetic operation cannot be expressed as a number. It is also the only value in JavaScript that is not equal to itself.

Although a number is conceptually a "mathematical value" and is always implicitly floating-point-encoded, JavaScript provides bitwise operators . When applying bitwise operators, the number is first converted to a 32-bit integer.

Note: Although bitwise operators can be used to represent several Boolean values within a single number using bit masking , this is usually considered a bad practice. JavaScript offers other means to represent a set of Booleans (like an array of Booleans, or an object with Boolean values assigned to named properties). Bit masking also tends to make the code more difficult to read, understand, and maintain.

It may be necessary to use such techniques in very constrained environments, like when trying to cope with the limitations of local storage, or in extreme cases (such as when each bit over the network counts). This technique should only be considered when it is the last measure that can be taken to optimize size.

BigInt type

The BigInt type is a numeric primitive in JavaScript that can represent integers with arbitrary magnitude. With BigInts, you can safely store and operate on large integers even beyond the safe integer limit ( Number.MAX_SAFE_INTEGER ) for Numbers.

A BigInt is created by appending n to the end of an integer or by calling the BigInt() function.

This example demonstrates where incrementing the Number.MAX_SAFE_INTEGER returns the expected result:

You can use most operators to work with BigInts, including + , * , - , ** , and % — the only forbidden one is >>> . A BigInt is not strictly equal to a Number with the same mathematical value, but it is loosely so.

BigInt values are neither always more precise nor always less precise than numbers, since BigInts cannot represent fractional numbers, but can represent big integers more accurately. Neither type entails the other, and they are not mutually substitutable. A TypeError is thrown if BigInt values are mixed with regular numbers in arithmetic expressions, or if they are implicitly converted to each other.

String type

The String type represents textual data and is encoded as a sequence of 16-bit unsigned integer values representing UTF-16 code units . Each element in the string occupies a position in the string. The first element is at index 0 , the next at index 1 , and so on. The length of a string is the number of UTF-16 code units in it, which may not correspond to the actual number of Unicode characters; see the String reference page for more details.

JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. String methods create new strings based on the content of the current string — for example:

  • A substring of the original using substring() .
  • A concatenation of two strings using the concatenation operator ( + ) or concat() .

Beware of "stringly-typing" your code!

It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:

  • It is easy to build complex strings with concatenation.
  • Strings are easy to debug (what you see printed is always what is in the string).
  • Strings are the common denominator of a lot of APIs ( input fields , local storage values, fetch() responses when using Response.text() , etc.) and it can be tempting to only work with strings.

With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.

Use strings for textual data. When representing complex data, parse strings, and use the appropriate abstraction.

Symbol type

A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called "atoms". The purpose of symbols is to create unique property keys that are guaranteed not to clash with keys from other code.

In computer science, an object is a value in memory which is possibly referenced by an identifier . In JavaScript, objects are the only mutable values. Functions are, in fact, also objects with the additional capability of being callable .

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax , a limited set of properties are initialized; then properties can be added and removed. Object properties are equivalent to key-value pairs. Property keys are either strings or symbols . When other types (such as numbers) are used to index objects, the values are implicitly converted to strings. Property values can be values of any type, including other objects, which enables building complex data structures.

There are two types of object properties: The data property and the accessor property . Each property has corresponding attributes . Each attribute is accessed internally by the JavaScript engine, but you can set them through Object.defineProperty() , or read them through Object.getOwnPropertyDescriptor() . You can read more about the various nuances on the Object.defineProperty() page.

Data property

Data properties associate a key with a value. It can be described by the following attributes:

The value retrieved by a get access of the property. Can be any JavaScript value.

A boolean value indicating if the property can be changed with an assignment.

A boolean value indicating if the property can be enumerated by a for...in loop. See also Enumerability and ownership of properties for how enumerability interacts with other functions and syntaxes.

A boolean value indicating if the property can be deleted, can be changed to an accessor property, and can have its attributes changed.

Accessor property

Associates a key with one of two accessor functions ( get and set ) to retrieve or store a value.

Note: It's important to recognize it's accessor property — not accessor method . We can give a JavaScript object class-like accessors by using a function as a value — but that doesn't make the object a class.

An accessor property has the following attributes:

A function called with an empty argument list to retrieve the property value whenever a get access to the value is performed. See also getters . May be undefined .

A function called with an argument that contains the assigned value. Executed whenever a specified property is attempted to be changed. See also setters . May be undefined .

A boolean value indicating if the property can be deleted, can be changed to a data property, and can have its attributes changed.

The prototype of an object points to another object or to null — it's conceptually a hidden property of the object, commonly represented as [[Prototype]] . Properties of the object's [[Prototype]] can also be accessed on the object itself.

Objects are ad-hoc key-value pairs, so they are often used as maps. However, there can be ergonomics, security, and performance issues. Use a Map for storing arbitrary data instead. The Map reference contains a more detailed discussion of the pros & cons between plain objects and maps for storing key-value associations.

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

Indexed collections: Arrays and typed Arrays

Arrays are regular objects for which there is a particular relationship between integer-keyed properties and the length property.

Additionally, arrays inherit from Array.prototype , which provides a handful of convenient methods to manipulate arrays. For example, indexOf() searches a value in the array and push() appends an element to the array. This makes Arrays a perfect candidate to represent ordered lists.

Typed Arrays present an array-like view of an underlying binary data buffer, and offer many methods that have similar semantics to the array counterparts. "Typed array" is an umbrella term for a range of data structures, including Int8Array , Float32Array , etc. Check the typed array page for more information. Typed arrays are often used in conjunction with ArrayBuffer and DataView .

Keyed collections: Maps, Sets, WeakMaps, WeakSets

These data structures take object references as keys. Set and WeakSet represent a collection of unique values, while Map and WeakMap represent a collection of key-value associations.

You could implement Map s and Set s yourself. However, since objects cannot be compared (in the sense of < "less than", for instance), neither does the engine expose its hash function for objects, look-up performance would necessarily be linear. Native implementations of them (including WeakMap s) can have look-up performance that is approximately logarithmic to constant time.

Usually, to bind data to a DOM node, one could set properties directly on the object, or use data-* attributes. This has the downside that the data is available to any script running in the same context. Map s and WeakMap s make it easy to privately bind data to an object.

WeakMap and WeakSet only allow garbage-collectable values as keys, which are either objects or non-registered symbols , and the keys may be collected even when they remain in the collection. They are specifically used for memory usage optimization .

Structured data: JSON

JSON ( J ava S cript O bject N otation) is a lightweight data-interchange format, derived from JavaScript, but used by many programming languages. JSON builds universal data structures that can be transferred between different environments and even across languages. See JSON for more details.

More objects in the standard library

JavaScript has a standard library of built-in objects. Read the reference to find out more about the built-in objects.

Type coercion

As mentioned above, JavaScript is a weakly typed language. This means that you can often use a value of one type where another type is expected, and the language will convert it to the right type for you. To do so, JavaScript defines a handful of coercion rules.

Primitive coercion

The primitive coercion process is used where a primitive value is expected, but there's no strong preference for what the actual type should be. This is usually when a string , a number , or a BigInt are equally acceptable. For example:

  • The Date() constructor, when it receives one argument that's not a Date instance — strings represent date strings, while numbers represent timestamps.
  • The + operator — if one operand is a string, string concatenation is performed; otherwise, numeric addition is performed.
  • The == operator — if one operand is a primitive while the other is an object, the object is converted to a primitive value with no preferred type.

This operation does not do any conversion if the value is already a primitive. Objects are converted to primitives by calling its [Symbol.toPrimitive]() (with "default" as hint), valueOf() , and toString() methods, in that order. Note that primitive conversion calls valueOf() before toString() , which is similar to the behavior of number coercion but different from string coercion .

The [Symbol.toPrimitive]() method, if present, must return a primitive — returning an object results in a TypeError . For valueOf() and toString() , if one returns an object, the return value is ignored and the other's return value is used instead; if neither is present, or neither returns a primitive, a TypeError is thrown. For example, in the following code:

Neither {} nor [] have a [Symbol.toPrimitive]() method. Both {} and [] inherit valueOf() from Object.prototype.valueOf , which returns the object itself. Since the return value is an object, it is ignored. Therefore, toString() is called instead. {}.toString() returns "[object Object]" , while [].toString() returns "" , so the result is their concatenation: "[object Object]" .

The [Symbol.toPrimitive]() method always takes precedence when doing conversion to any primitive type. Primitive conversion generally behaves like number conversion, because valueOf() is called in priority; however, objects with custom [Symbol.toPrimitive]() methods can choose to return any primitive. Date and Symbol objects are the only built-in objects that override the [Symbol.toPrimitive]() method. Date.prototype[Symbol.toPrimitive]() treats the "default" hint as if it's "string" , while Symbol.prototype[Symbol.toPrimitive]() ignores the hint and always returns a symbol.

Numeric coercion

There are two numeric types: Number and BigInt . Sometimes the language specifically expects a number or a BigInt (such as Array.prototype.slice() , where the index must be a number); other times, it may tolerate either and perform different operations depending on the operand's type. For strict coercion processes that do not allow implicit conversion from the other type, see number coercion and BigInt coercion .

Numeric coercion is nearly the same as number coercion , except that BigInts are returned as-is instead of causing a TypeError . Numeric coercion is used by all arithmetic operators, since they are overloaded for both numbers and BigInts. The only exception is unary plus , which always does number coercion.

Other coercions

All data types, except Null, Undefined, and Symbol, have their respective coercion process. See string coercion , boolean coercion , and object coercion for more details.

As you may have noticed, there are three distinct paths through which objects may be converted to primitives:

  • Primitive coercion : [Symbol.toPrimitive]("default") → valueOf() → toString()
  • Numeric coercion , number coercion , BigInt coercion : [Symbol.toPrimitive]("number") → valueOf() → toString()
  • String coercion : [Symbol.toPrimitive]("string") → toString() → valueOf()

In all cases, [Symbol.toPrimitive]() , if present, must be callable and return a primitive, while valueOf or toString will be ignored if they are not callable or return an object. At the end of the process, if successful, the result is guaranteed to be a primitive. The resulting primitive is then subject to further coercions depending on the context.

  • JavaScript Data Structures and Algorithms by Oleksii Trekhleb
  • Computer Science in JavaScript by Nicholas C. Zakas

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript data types, javascript has 8 datatypes.

String Number Bigint Boolean Undefined Null Symbol Object

The Object Datatype

The object data type can contain both built-in objects , and user defined objects :

Built-in object types can be:

objects, arrays, dates, maps, sets, intarrays, floatarrays, promises, and more.

A JavaScript variable can hold any type of data.

The Concept of Data Types

In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?

JavaScript will treat the example above as:

When adding a number and a string, JavaScript will treat the number as a string.

JavaScript evaluates expressions from left to right. Different sequences can produce different results:

JavaScript:

In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as strings.

Advertisement

JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

JavaScript Strings

A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

You will learn more about strings later in this tutorial.

JavaScript Numbers

All JavaScript numbers are stored as decimal numbers (floating point).

Numbers can be written with, or without decimals:

Exponential Notation

Extra large or extra small numbers can be written with scientific (exponential) notation:

Most programming languages have many number types:

Whole numbers (integers): byte (8-bit), short (16-bit), int (32-bit), long (64-bit)

Real numbers (floating-point): float (32-bit), double (64-bit).

Javascript numbers are always one type: double (64-bit floating point).

You will learn more about numbers later in this tutorial.

JavaScript BigInt

All JavaScript numbers are stored in a 64-bit floating-point format.

JavaScript BigInt is a new datatype ( ES2020 ) that can be used to store integer values that are too big to be represented by a normal JavaScript Number.

You will learn more about BigInt later in this tutorial.

JavaScript Booleans

Booleans can only have two values: true or false .

Booleans are often used in conditional testing.

You will learn more about booleans later in this tutorial.

JavaScript Arrays

JavaScript arrays are written with square brackets.

Array items are separated by commas.

The following code declares (creates) an array called cars , containing three items (car names):

Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

You will learn more about arrays later in this tutorial.

JavaScript Objects

JavaScript objects are written with curly braces {} .

Object properties are written as name:value pairs, separated by commas.

The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.

You will learn more about objects later in this tutorial.

The typeof Operator

You can use the JavaScript typeof operator to find the type of a JavaScript variable.

The typeof operator returns the type of a variable or an expression:

You will learn more about typeof later in this tutorial.

In JavaScript, a variable without a value, has the value undefined . The type is also undefined .

Any variable can be emptied, by setting the value to undefined . The type will also be undefined .

Empty Values

An empty value has nothing to do with undefined .

An empty string has both a legal value and a type.

Test Yourself With Exercises

Use comments to describe the correct data type of the following variables:

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

TutorialsTonight Logo

JAVASCRIPT ASSIGNMENT OPERATORS

In this tutorial, you will learn about all the different assignment operators in javascript and how to use them in javascript.

Assignment Operators

In javascript, there are 16 different assignment operators that are used to assign value to the variable. It is shorthand of other operators which is recommended to use.

The assignment operators are used to assign value based on the right operand to its left operand.

The left operand must be a variable while the right operand may be a variable, number, boolean, string, expression, object, or combination of any other.

One of the most basic assignment operators is equal = , which is used to directly assign a value.

javascript assignment operator

Assignment Operators List

Here is the list of all assignment operators in JavaScript:

In the following table if variable a is not defined then assume it to be 10.

Operator Description Example Equivalent to
= a = 10 a = 10
+= a += 10 a = a + 10
-= a -= 10 a = a - 10
*= a *= 10 a = a * 10
/= a /= 10 a = a / 10
%= a %= 10 a = a % 10
**= a **= 2 a = a ** 2
<<= a <<= 1 a = a << 1
>>= a >>= 2 a = a >> 2
>>>= a >>>= 1 a = a >>> 1
&= a &= 4 a = a & 4
|= a |= 2 a = a | 2
^= a ^= 5 a = a ^ 5
&&= a &&= 3 a = a && 3
||= a ||= 4 a = a || 4
??= a ??= 2 a = a ?? 2

Assignment operator

The assignment operator = is the simplest value assigning operator which assigns a given value to a variable.

The assignment operators support chaining, which means you can assign a single value in multiple variables in a single line.

Addition assignment operator

The addition assignment operator += is used to add the value of the right operand to the value of the left operand and assigns the result to the left operand.

On the basis of the data type of variable, the addition assignment operator may add or concatenate the variables.

Subtraction assignment operator

The subtraction assignment operator -= subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.

If the value can not be subtracted then it results in a NaN .

Multiplication assignment operator

The multiplication assignment operator *= assigns the result to the left operand after multiplying values of the left and right operand.

Division assignment operator

The division assignment operator /= divides the value of the left operand by the value of the right operand and assigns the result to the left operand.

Remainder assignment operator

The remainder assignment operator %= assigns the remainder to the left operand after dividing the value of the left operand by the value of the right operand.

Exponentiation assignment operator

The exponential assignment operator **= assigns the result of exponentiation to the left operand after exponentiating the value of the left operand by the value of the right operand.

Left shift assignment

The left shift assignment operator <<= assigns the result of the left shift to the left operand after shifting the value of the left operand by the value of the right operand.

Right shift assignment

The right shift assignment operator >>= assigns the result of the right shift to the left operand after shifting the value of the left operand by the value of the right operand.

Unsigned right shift assignment

The unsigned right shift assignment operator >>>= assigns the result of the unsigned right shift to the left operand after shifting the value of the left operand by the value of the right operand.

Bitwise AND assignment

The bitwise AND assignment operator &= assigns the result of bitwise AND to the left operand after ANDing the value of the left operand by the value of the right operand.

Bitwise OR assignment

The bitwise OR assignment operator |= assigns the result of bitwise OR to the left operand after ORing the value of left operand by the value of the right operand.

Bitwise XOR assignment

The bitwise XOR assignment operator ^= assigns the result of bitwise XOR to the left operand after XORing the value of the left operand by the value of the right operand.

Logical AND assignment

The logical AND assignment operator &&= assigns value to left operand only when it is truthy .

Note : A truthy value is a value that is considered true when encountered in a boolean context.

Logical OR assignment

The logical OR assignment operator ||= assigns value to left operand only when it is falsy .

Note : A falsy value is a value that is considered false when encountered in a boolean context.

Logical nullish assignment

The logical nullish assignment operator ??= assigns value to left operand only when it is nullish ( null or undefined ).

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Latest commit

File metadata and controls, javascript basics: data types.

JavaScript Basics - Data types

Sketchnote by Tomomi Imura

Pre-Lecture Quiz

Pre-lecture quiz

This lesson covers the basics of JavaScript, the language that provides interactivity on the web.

You can take this lesson on Microsoft Learn !

Variables

🎥 Click the images above for videos about variables and data types

Let's start with variables and the data types that populate them!

Variables store values that can be used and changed throughout your code.

Creating and declaring a variable has the following syntax [keyword] [name] . It's made up of the two parts:

  • Keyword . Keywords can be let or var .

✅ The keyword let was introduced in ES6 and gives your variable a so called block scope . It's recommended that you use let over var . We will cover block scopes more in depth in future parts.

  • The variable name , this is a name you choose yourself.

Task - working with variables

Declare a variable . Let's declare a variable using the let keyword:

myVariable has now been declared using the let keyword. It currently doesn't have a value.

Assign a value . Store a value in a variable with the = operator, followed by the expected value.

Note: the use of = in this lesson means we make use of an "assignment operator", used to set a value to a variable. It doesn't denote equality.

myVariable has now been initialized with the value 123.

Refactor . Replace your code with the following statement.

The above is called an explicit initialization when a variable is declared and is assigned a value at the same time.

Change the variable value . Change the variable value in the following way:

Once a variable is declared, you can change its value at any point in your code with the = operator and the new value.

✅ Try it! You can write JavaScript right in your browser. Open a browser window and navigate to Developer Tools. In the console, you will find a prompt; type let myVariable = 123 , press return, then type myVariable . What happens? Note, you'll learn more about these concepts in subsequent lessons.

Declaration and initialization of a constant follows the same concepts as a variable, with the exception of the const keyword. Constants are typically declared with all uppercase letters.

Constants are similar to variables, with two exceptions:

Must have a value . Constants must be initialized, or an error will occur when running code.

Reference cannot be changed . The reference of a constant cannot be changed once initialized, or an error will occur when running code. Let's look at two examples:

Simple value . The following is NOT allowed:

Object reference is protected . The following is NOT allowed.

Object value is not protected . The following IS allowed:

Above you are changing the value of the object but not the reference itself, which makes it allowed.

Note, a const means the reference is protected from reassignment. The value is not immutable though and can change, especially if it's a complex construct like an object.

Variables can store many different types of values, like numbers and text. These various types of values are known as the data type . Data types are an important part of software development because it helps developers make decisions on how the code should be written and how the software should run. Furthermore, some data types have unique features that help transform or extract additional information in a value.

✅ Data Types are also referred to as JavaScript data primitives, as they are the lowest-level data types that are provided by the language. There are 7 primitive data types: string, number, bigint, boolean, undefined, null and symbol. Take a minute to visualize what each of these primitives might represent. What is a zebra ? How about 0 ? true ?

In the previous section, the value of myVariable was a number data type.

let myVariable = 123;

Variables can store all types of numbers, including decimals or negative numbers. Numbers also can be used with arithmetic operators, covered in the next section .

Arithmetic Operators

There are several types of operators to use when performing arithmetic functions, and some are listed here:

Symbol Description Example
: Calculates the sum of two numbers
: Calculates the difference of two numbers
: Calculates the product of two numbers
: Calculates the quotient of two numbers
: Calculates the remainder from the division of two numbers

✅ Try it! Try an arithmetic operation in your browser's console. Do the results surprise you?

Strings are sets of characters that reside between single or double quotes.

  • 'This is a string'
  • "This is also a string"
  • let myString = 'This is a string value stored in a variable';

Remember to use quotes when writing a string, or else JavaScript will assume it's a variable name.

Formatting Strings

Strings are textual, and will require formatting from time to time.

To concatenate two or more strings, or join them together, use the + operator.

✅ Why does 1 + 1 = 2 in JavaScript, but '1' + '1' = 11? Think about it. What about '1' + 1 ?

Template literals are another way to format strings, except instead of quotes, the backtick is used. Anything that is not plain text must be placed inside placeholders ${ } . This includes any variables that may be strings.

You can achieve your formatting goals with either method, but template literals will respect any spaces and line breaks.

✅ When would you use a template literal vs. a plain string?

Booleans can be only two values: true or false . Booleans can help make decisions on which lines of code should run when certain conditions are met. In many cases, operators assist with setting the value of a Boolean and you will often notice and write variables being initialized or their values being updated with an operator.

  • let myTrueBool = true
  • let myFalseBool = false

✅ A variable can be considered 'truthy' if it evaluates to a boolean true . Interestingly, in JavaScript, all values are truthy unless defined as falsy .

🚀 Challenge

JavaScript is notorious for its surprising ways of handling datatypes on occasion. Do a bit of research on these 'gotchas'. For example: case sensitivity can bite! Try this in your console: let age = 1; let Age = 2; age == Age (resolves false -- why?). What other gotchas can you find?

Post-Lecture Quiz

Post-lecture quiz

Review & Self Study

Take a look at this list of JavaScript exercises and try one. What did you learn?

Data Types Practice

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript null and undefined

JavaScript typeof Operator

JavaScript Type Conversion

JavaScript Booleans

JavaScript Data Types

Data types represent the different kinds of values we can use in JavaScript.

There are altogether 8 basic data types in JavaScript.

Data Type Description Example
Textual data. , , etc.
An integer or a floating-point number. , , , etc.
An integer with arbitrary precision. , , etc.
Any of two values: or . and
A data type whose variable is not initialized.
Denotes a value.
A data type whose instances are unique and immutable.
Key-value pairs of collection of data.

Note: JavaScript data types are divided into primitive and non-primitive types.

  • Primitive Data Types: They can hold a single simple value. String , Number , BigInt , Boolean , undefined , null , and Symbol are primitive data types.
  • Non-Primitive Data Types: They can hold multiple values. Objects are non-primitive data types.

A string represents textual data. It contains a sequence of characters. For example, "hello" , "JavaScript" , etc.

In JavaScript, strings are surrounded by quotes:

  • Single quotes: 'Hello'
  • Double quotes: "Hello"
  • Backticks: `Hello`

For example,

In a string, we can either use single quotes or double quotes. However, it is recommended to use double quotes.

Note: It is illegal to mismatch quotes in strings. For example, the strings 'hello" and "world' are enclosed inside one single quote and one double quote, which results in an error.

To learn more about strings, visit JavaScript String .

In JavaScript, the number type represents numeric values (both integers and floating-point numbers).

  • Integers - Numeric values without any decimal parts. Example: 3 , -74 , etc.
  • Floating-Point - Numeric values with decimal parts. Example: 3.15 , -1.3 , etc.

To learn more about numbers, visit JavaScript Number .

Special Numeric Values

JavaScript can also represent special numeric values such as Infinity , -Infinity , and NaN (Not-a-Number). For example,

  • JavaScript BigInt

BigInt is a type of number that can represent very large or very small integers beyond the range of the regular number data type.

Note: The regular number data type can handle values less than (2^53 - 1) and greater than -(2^53 - 1) .

A BigInt number is created by appending n to the end of an integer. For example,

Note: BigInt was introduced in a newer version of JavaScript (ES11) and is not supported by many browsers, including Safari. To learn more, visit JavaScript BigInt support .

You can't mix BigInt and number

In JavaScript, you can't mix BigInt and number values (for instance, by performing arithmetic operations between them).

  • JavaScript Boolean

A Boolean data can only have one of two values: true or false . For example,

If you want to learn more about booleans, visit JavaScript Booleans .

  • JavaScript undefined

In JavaScript, undefined represents the absence of a value.

If a variable is declared but the value is not assigned, then the value of that variable will be undefined . For example,

It is also possible to explicitly assign undefined as a variable value. For example,

Note: You should avoid explicitly assigning undefined to a variable. Usually, we assign null to variables to indicate "unknown" or "empty" values.

  • JavaScript null

In JavaScript, null represents "no value" or "nothing." For example,

Here, let number = null; indicates that the number variable is set to have no value.

Visit JavaScript null and undefined to learn more.

A Symbol is a unique and primitive value. This data type was introduced in ES6 .

When you create a Symbol , JavaScript guarantees that it is distinct from all other symbols, even if they have the same descriptions. For example,

Here, we have used === to compare value1 and value2 . It returns true if the two values are exactly the same. Otherwise, it returns false .

Though both value1 and value2 contain "programiz" , JavaScript treats them as different since they are of the Symbol type. Hence, value1 === value2 returns false .

To learn more, visit JavaScript Symbol .

  • JavaScript Object

An Object holds data in the form of key-value pairs. For example,

Here, we have created an object named student that contains key-value pairs:

Key Value

To learn more, visit JavaScript Objects .

More on JavaScript Data Types

You can use the typeof operator to find the data type of a variable. For example,

Note: Notice that typeof returned object for the null type. This has been a known issue in JavaScript since its first release.

JavaScript determines the type of a variable based on the value assigned to it.

As a result, changing the value of a variable can also change its type, provided the new value is of a different type. For example,

Table of Contents

  • Introduction

Video: JavaScript Data Types

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

JavaScript Tutorial

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

Variables and Datatypes in JavaScript

Variables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand.

In JavaScript, variables are used to store and manage data. They are created using the var , let , or const keyword.

1. var Keyword

The var keyword is used to declare a variable. It has a function-scoped or globally-scoped behavior.

Example:  In this example, we will declare variables using var.

2. let Keyword

The let keyword is a block-scoped variables. It’s commonly used for variables that may change their value.

Example:  In this example, we will declare variables using let.

const Keyword

The const keyword declares variables that cannot be reassigned. It’s block-scoped as well.

Example:  In this example, we will declare the variable using the const keyword.

JavaScript is a  dynamically typed  (also called loosely typed) scripting language. In JavaScript, variables can receive different data types over time. The latest ECMAScript standard defines eight data types Out of which seven data types are  Primitive (predefined)  and one  complex or Non-Primitive .

Primitive Data Types

The predefined data types provided by JavaScript language are known as primitive data types. Primitive data types are also known as in-built data types.

  • Number:  JavaScript numbers are always stored in double-precision 64-bit binary format IEEE 754. Unlike other programming languages, you don’t need int, float, etc to declare different numeric values.
  • String:  JavaScript Strings are similar to sentences. They are made up of a list of characters, which is essentially just an “array of characters, like “Hello GeeksforGeeks” etc.
  • Boolean:  Represent a logical entity and can have two values: true or false.
  • Null:  This type has only one value that is  null.
  • Undefined:  A variable that has not been assigned a value is  undefined.
  • Symbol:  Symbols return unique identifiers that can be used to add unique property keys to an object that won’t collide with keys of any other code that might add to the object.
  • BigInt:  BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 2^53-1.

Non-Primitive Data Types

The data types that are derived from primitive data types of the JavaScript language are known as non-primitive data types. It is also known as derived data types or reference data types.

  • Object:  It is the most important data type and forms the building blocks for modern JavaScript. We will learn about these data types in detail in further articles.

FAQs – Variables and DataTypes in JavaScript

What are the different data types in javascript.

JavaScript has several basic data types including string , number , boolean , undefined , null , symbol , and bigint . There are also complex data types like object , which includes arrays and functions.

How do you declare a variable in JavaScript?

In JavaScript, you can declare a variable using var, let, or const. let and const were introduced in ES6 and are preferred over var because of their block-scoping and other advantages.

What is the difference between let, var, and const in JavaScript?

var is function-scoped, while let and const are block-scoped. let allows you to reassign a value to a variable, while const does not, meaning variables declared with const cannot be reassigned after their initial assignment.

What is the difference between null and undefined in JavaScript?

undefined means a variable has been declared but has not yet been assigned a value. null is an assignment value that represents “no value” or “empty”.

How can you check the data type of a variable in JavaScript?

You can use the typeof operator to determine the data type of a variable in JavaScript. For example, typeof 42 returns “number”, and typeof “hello” returns “string”.

author

Please Login to comment...

Similar reads.

  • Web Technologies
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

DEV Community

DEV Community

Teresa Holfeld

Posted on Oct 31, 2020

JavaScript: Variables, Data Types and Operators

So you want to learn how to code. But what is a good way to start? There are plenty of options: courses , books , games , some even targeted at children. Yes, Children! If a child can do it, how hard can it be, right?

In this post, I show you the fundamentals you need at the beginning. These fundamentals are mostly the same for any programming language. All programming languages use the same principles: variables, logical operators, decisions, loops and functions. Once you understand these, you will begin to think like a coder.

Coding has, in fact, more to do with logical thinking than with math. For learning to code it’s even more of an advantage to have an affinity for languages. Sure, math skills are relevant for some fields of computer science, but more in the academic realm of data science or machine learning. In their day to day work, programmers usually don’t use more than basic arithmetics. Which supports our claim: even a child can learn programming.

Let’s take a look at the most basic coding concepts: variables, data types and operators. For demonstration purposes, we will use JavaScript, because it is a widely used language. However, these concepts apply to any other language as well. For showing you the fundamentals, it wouldn’t matter which language we used here. This characteristic is called language agnostic .

💡 The word ”agnostic” is derived from ancient Greek for “not knowing”. Hence, language agnostic means “not knowing the specific language”.

Here, the irrelevant programming language in our examples is JavaScript.

Hello World!

You can follow the code examples of this article on repl.it . Repl.it is an online editor and does not require installation. You can also start your own cloud editor by choosing JavaScript in the footer of the homepage. This is what the user interface looks like:

Repl.it editor

On the left is the input field where we’ll write our JavaScript code. On the right, you’ll see the output. Clicking on the green “run” button at the header’s center will run the program. Try it out by typing the following line into input:

This is what should appear in the output on the right:

Repl.it console output

If it looks like this, you did it right. You might wonder what this green undefined is, but simply ignore it for now.

With this short line, you ran the Hello World program. It’s what a programmer always does at the beginning to test a programming language. Check out the Hello World programs of other languages in the extensive Hello-World Collection .

After we have tested our repl.it editor with the Hello World program, we now define our first variable:

Running this short command will output Teresa on the right.

You can think of a variable as a box. You put something into the box (in this case Teresa ) and label the box (in this case myName ). Each time a command (in this case console.log ) uses the variable ( myName ), it’s as if it would use the variable’s content ( Teresa ). To practice, change the variable’s content or name and see what happens!

You can also join multiple pieces of text together:

The output now shows: Hello my name is Teresa . The box of variable text now consists of the text Hello my name is Teresa . The plus sign + in the middle joins both texts together. Note the space after is . Without it, variable text would mistakenly be "Hello my name isTeresa" .

In programming languages, texts are called strings . This has to do with a text being a string of characters being put together. A string can have any length, i.e. any number of characters. The content of variable text ( Teresa ) has a length of 6, because it consists of 6 characters.

String variables can also be joined with other variables:

This is where it gets interesting. You can change the content of the variable myName , which you may have used several times in your code. With this little change in the variable, the name changes throughout your output. Practice by changing the variable’s content in various ways and check what this does to your output.

The keyword var says: this is a new variable we are creating. Then, at console.log you won’t write out var because the variable already exists.

A data type is the type of content of a variable. You already know one: string . A string basically is a text, a string of characters put together.

There are other data types as well. You can, for example, use numbers as variables:

The variable number here has the content 5 . Running the command console.log with the variable will show 5 .

This sort of number is called integer . Integers can be positive or negative. You can try it with a negative number: put a negative sign - before 5 and run your code.

You can use decimals, too:

In programming this is called a floating point number , or short float .

Previously, you were using the plus + sign to join strings together. You can also use it to join strings with integers or floating point numbers. You will probably easily recognize what the output of this is going to be:

There is one more data type which is very important: true or false . In logic, a statement can be either true or false. This data type is called boolean .

Instead of false you could also write true . Try both and see how this changes the output.

Of course you can also join strings with booleans:

So, why do we have variables? Let’s see what we can do with them, and have a closer look at operators .

Arithmetic Operators

Operators are special characters that we can use in programming languages to do certain operations. There are arithmetic operators like plus + , minus - , multiply * , and divide by / . Then, there are also so-called logical operators, which we’ll explain shortly.

By the way, we already used two operators:

The equality sign = and the plus sign + . The equality sign = is an assignment operator . It means that the content on the right (in our case: "Hello my name is " + myName ) is assigned to the variable on the left (in our case: var text ).

The plus sign + is also an operator. But here it is not an arithmetic operator. With strings, + is used as a concatenation operator , which joins several strings or strings and numbers together to form one long string.

With numbers, you use the plus sign + as arithmetic operator. It will add one number to the other. Similarly, you can use the operators minus - , multiply * , divide by / , and modulo % . We will explain what modulo % does in a bit (it does not mean percentage).

Let’s first try them with two integers:

The output will be: The sum is 17 . The + adds the two integers. In the same way, - subtracts an integer from another. Let’s take our two variables a and b:

This is easy, isn’t it? The output will be: The difference is 7 .

For practice, try this with * , multiplication. Of course you need to adjust the sentence to read “The product is “. The correct result should be 60. And what do we get by dividing, / , the two?

The result is 2.4. It has a decimal point, so it’s a float! You can also assign the result of the operation to another variable. We’ll call it “ratio”.

The quotient of a and b is a float, so the variable ratio is of the data type float as well. Operations with floats work in the same way as integers. Try it out by changing variables a and b to floats.

That’s much harder to calculate in your head, and we start to see how doing this with a programming language can be of much help. Computers are much better at arithmetic than humans. Experienced programmers usually leave that to the computer. All they need to know is how to express these calculations in their programming language.

The % sign is called modulo . The modulo operator is a bit special. You use it to calculate the remainder of a division.

In our example, the result is 2. How did we get there? Well, 12 / 5 = 2 with remainder 2. The number 5 fits 2 entire times into 12, and leave 2 not accounted for. The result of the modulo operator is always the remainder. If we changed our variable a to 13, we would get modulo 3.

Conditional Statements and Relational Operators

At some point, you’ll want to create statements which run on conditions. Maybe you have already heard of if-else statements . This is how it works:

We verify the user’s age. Is the value of the userAge variable greater or equal than 18? If it is, show the toast “Have a Beer!”. If their age is less than 18, meaning the condition is not met, show the toast “Have a Soda!”.

We need the keywords if and else as well as the curly brackets following the keywords. Is a condition met, the program runs the statement in brackets after if (…) . Is the condition not met, the program runs any statement after else . Try it out by playing with the value of the userAge variable.

Let’s take a closer look at what’s in the round brackets after the if : userAge >= 18 . >= is a relational operator . It means greater or equal than. The other relational operators are:

The result of a relational operator is either true or false, therefore a boolean. You can save it to a variable as well, which then is of the data type boolean. You will see this if you create a variable comparing a and b:

The output is false . This proves our variable result is of the boolean data type.

You can always use variables to store intermediate results. In the if-statement, you can then use this variable. We could write our beer-soda-example like:

An if-statement can contain an operation ( userAge >= 18 ) or a variable ( isOldEnough ). If you use a variable in the if-statement, the variable has to be a boolean. Otherwise, it won’t work.

Logical operators

When writing if-else-statements, we can logically concatenate several conditions. Let’s say in our example, we wanted a teenager, 16 and older, to be allowed to drink beer when a parent is with them. We would express it like this:

The else-command is omitted here for better focus. We’ve concatenated the two conditions ( userAge >= 16 ) and ( withParentalGuidance ) with an AND-operator ( && ). In total, there are three logical operators:

The ! , you’ve already seen as != (not equal to). AND and OR operators are placed between the two conditions to be concatenated (as shown in our example). It is slightly different with the NOT operator which is placed before the condition to be negated.

With NOT, a statement is logically reversed:

You can concatenate as many conditions as you like. Brackets aren’t always necessary, but they help–especially at the beginning–to better understand the logic.

Let’s further specify our example from before. If someone is older than 18 OR older than 16 AND with a guardian, they get a beer:

When reversing a condition with a NOT operator ( ! ), keep in mind to also reverse any relational operator ( >= ). For our example (userAge >= 18) is the same as !(userAge < 18) .

We turned greater or equal than ( >= ) into less than ( < ), but not into less or equal than as we want the condition to hold true if userAge is exactly 18.

The opposite of >= is < The opposite of <= is >

Put the other way around:

The opposite of < is >= The opposite of > is <=

If we now want to define that 16 and 17 year olds are allowed to drink beer with their parents’ permission, but only up to a maximum of 2 beers, how would we express that? It leads us to an additional statement: else if .

You may write many more else-if-statements than one, but we’ll leave it at that for now.

To practice, try writing a program that has 3 variables and gives an output of the greatest of these three variables. We give you a hint: Within an if you can nest another if into curly brackets:

I prepared the solution to this exercise on repl.it . For any question, join our Slack and ask away. If you have, post a link to your code, so I can help you better.

This has been quite a bit of information! Great job at staying with us! Review the individual operators step by step until you are able to apply them on your own. I will build on this in another post where I’ll discuss loops and functions.

Btw, I run a coding school in the north of Germany, called Hamburg Coding School. We teach a classroom course there where we cover exactly these topics: Learn to Code . Even if you can't participate locally, feel free to join our Slack and say hi! 👋😊 We welcome and help everyone there.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

uicraft_by_pratik profile image

Exploring Modern JavaScript ⚡Functions: New Features and Best Practices

Pratik Tamhane - Aug 29

vyan profile image

Implementing a Simple Page View Tracker in Your React App

Vishal Yadav - Aug 29

dharamgfx profile image

⚔️ JavaScript vs. TypeScript: The Language Showdown! 🤯

Dharmendra Kumar - Aug 29

gadekar_sachin profile image

Supercharge Your Frontend Skills: 8 Must-Have Tools for Developers in 2024 🚀

Sachin Gadekar - Aug 29

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Exploring the Various Data Types in JavaScript: From Primitives to Objects

Data types in JavaScript describe the different types or kinds of data that you will be working with and storing in variables. It's important that you learn each of these data types because otherwise data can get stored in an improper format which will result in issues in your code later on.n JavaScript, data types are used to classify different types of data and define the type of values that a variable can hold. The main data types in JavaScript include:

Primitive data types: These are the basic data types that include numbers, strings, booleans, and special values like null and undefined.

Data Type Description
String A string is a collection of alphanumeric characters.
Number Numbers are for numbers. We can't put a letter on here.
Boolean Booleans have two values. True and false.
Null and Undefined null and undefined stand for empty. That means they have no value assigned to them.
Symbols Symbol is a primitive data type of JavaScript.It's a very peculiar data type. Once you create a symbol, its value is kept private and for internal use.
Array An array is a type of object used for storing multiple values in single variable.
Object Literals It is a comma-separated list of name-value pairs wrapped in curly braces.
Date JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications.

JavaScript is a loosely typed language, which means that the data type of a variable does not have to be explicitly declared. Instead, JavaScript automatically determines the data type of a variable based on the value assigned to it. However, it's a good practice to be aware of the data types in JavaScript as you work with variables and write your code.

In addition to these basic data types, JavaScript also has some special data types like Symbol and bigInt, which are used for specific purposes.

Source Code

List of programs.

  • JavaScript Introduction
  • Basic Program in JavaScript
  • Console in JavaScript
  • var , let , const in JavaScript
  • DataTypes in JavaScript
  • Type Conversion in JavaScript
  • Type Coercion in JavaScript
  • Arithmetic Operation in JavaScript
  • Assignment Operators in JavaScript
  • Comparison Operators in JavaScript
  • Relational Operators in JavaScript
  • Logical Operators in JavaScript
  • Strict Equality or Identity Operators in JavaScript
  • Ternary Operators in JavaScript
  • Bitwise Operators in JavaScript
  • Nullish Coalescing Operators in JavaScript
  • Increment or Decrement Operators in JavaScript
  • If Statement in JavaScript
  • If Else Statement in JavaScript
  • Else If Statement in JavaScript
  • Nested If Statement in JavaScript
  • Switch Statement in JavaScript
  • Combining Cases Statement in JavaScript
  • While Loop in JavaScript
  • Do While Loop in JavaScript
  • For Loop in JavaScript
  • For Of Loop in JavaScript
  • For In Loop in JavaScript
  • Looping over objects by converting to an array in JavaScript
  • Break in JavaScript
  • Continue in JavaScript
  • Labeled Blocks in JavaScript
  • Math Functions in JavaScript
  • String Function in JavaScript
  • Template Literals in JavaScript
  • Array Function in JavaScript
  • Primitive and Reference Data Types
  • Multiple ways to clone an array
  • Use of const for Creating Arrays
  • Array and Object De-structuring
  • Arrays & Object
  • Creating Objects
  • Dot Notation and Bracket Notation
  • Iterating Through JavaScript Objects
  • Computed Property Names
  • Spread Operator
  • Objects inside Arrays
  • Function in JavaScript
  • Block Scope and Function Scope
  • Rest Parameter vs Spread
  • Parameter Destructuring in JavaScript
  • Callback Functions in JavaScript
  • Closure Functions
  • forEach in JavaScript
  • Filter Practical Samples
  • Map Practical Samples
  • Reduce Practical Samples
  • Optional Chaining in JavaScript
  • Function Inside Object
  • Call Apply and Bind in JavaScript
  • Arrow Function vs this Keyword
  • Creating Objects in JavaScript
  • Prototype and Prototypal Inheritance in JavaScript
  • Class and Inheritance in JavaScript
  • Getter and Setter in JavaScript
  • Static Methods and Properties
  • Sets in Javascript
  • Exploring Map in JavaScript
  • Destructuring Assignment
  • Document Object Model
  • DOM Family Structure
  • DOM Family Tree Method
  • DOM Traversing Method
  • DOM Create Method
  • DOM Output Possibilities
  • DOM ClassList and Attributes
  • DOM Mouse Events
  • DOM Keyboard Events
  • DOM Form Events
  • DOM Touch Events
  • Example of Touch Events
  • Promise in Javascript
  • Async and await in Javascript
  • Fetch api in Javascript
  • Event Loop in Javascript
  • Event Bubbling in Javascript
  • Event Delegation in Javascript
  • Debounce function in Javascript
  • Array Local Storage in Javascript
  • Object Local Storage in Javascript
  • Template Theme Change in Javascript
  • Session Storage in Javascript
  • Change Content using getElementById
  • Change Image in Javascript
  • Change Style in Javascript
  • Hide and Show Paragraph in Javascript

JS Practical Questions & Answers

  • forEach Programs
  • Filter Programs
  • Map Programs
  • Reduce Programs

JS Practical Project

  • Automatic Countdown Timer
  • Digital Clock in JS
  • Analog Clock
  • Stylish Stop Clock
  • CSS Code Tools
  • Sticky Note
  • Photo Gallery
  • Password Generator
  • Product Filter
  • Product Cart Slider
  • Product Rating
  • Shopping Cart
  • QR Code Generator
  • Tic Tac Toe Game
  • Image Carousel
  • Tab Control
  • Income Expense Tracker
  • Auto Complete Text Box
  • Custom Password Text box
  • Creating Tag Input
  • Custom Form Validation
  • Dependent Select Box
  • Custom Context Menu
  • HTML Table to CSV File
  • Custom event Calendar
  • E-Commerce Product Filter
  • Custom Testimonial
  • Dynamic Circular Progress Bar
  • Interactive Image Gallery
  • Customer Review Slider

JS Membership Project

  • Countdown Timer
  • Digital Timer Clock in JS
  • Analog Wall Clock
  • Stylish Stop Watch
  • Click to Copy Code
  • Auto Complete Text Box Highlighter
  • Dynamic Tab Control

Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions

  • Show all results for " "

JavaScript Variables and Data Types Quiz

JavaScript Variables and Data Types Quiz

More actions.

  • PDF Questions
  • Make a copy

Questions and Answers

What will be the output of the following javascript code snippet alert('this is an important message');.

  • A confirm box
  • A prompt box
  • An alert box with the message 'This is an important message!' (correct)

Which of the following is an assignment operator in JavaScript?

  • = (correct)

In JavaScript's logical operators, what will be the result of true || false ?

  • true (correct)

Which control structure in JavaScript is used for selecting between two different paths based on a condition?

<p>Simple if-else statement</p> Signup and view all the answers

Under which category do the following operators fall in JavaScript: '===', '!==', '>=', '<'?

<p>Comparison Operators</p> Signup and view all the answers

Which JavaScript operator can be used to assign a value only if a condition is true?

<p>? :</p> Signup and view all the answers

Which keyword is used to declare a constant variable in JavaScript?

<p>const</p> Signup and view all the answers

What is the correct way to initialize a variable 'age' to 20 in JavaScript?

<p>var age = 20;</p> Signup and view all the answers

Which of the following is NOT a valid way to declare multiple variables in JavaScript?

<p>x, y, z;</p> Signup and view all the answers

When assigning a value to a variable in JavaScript, what symbol is used for comparison?

<p>=</p> Signup and view all the answers

Which of the following is a correct way to declare and initialize a constant variable in JavaScript?

<p>const z = 8;</p> Signup and view all the answers

What message will be displayed if the 'mark' variable is 45 in the first code snippet?

<p>Fail</p> Signup and view all the answers

In the second code snippet, what message will be displayed if the user enters -7?

<p>The number is either a negative number or 0</p> Signup and view all the answers

What will be the output if the condition in line 38 is false?

<p>Perform actions</p> Signup and view all the answers

Are the control structures in lines 37 and 38 of the text equivalent?

<p>No</p> Signup and view all the answers

What would be the result of the time assignment operation in line 40 of the text?

<p>Assignment of value 10 to time</p> Signup and view all the answers

If the 'time' variable is 10, what would be the output of the condition in line 40 of the text?

<p>'time' is equal to 10</p> Signup and view all the answers

Study Notes

Variables and data types.

  • In JavaScript, all numbers are represented as floating-point values.
  • Variables are declared using the var and let keywords.
  • Examples of variable declarations: var age; , var smallNumber; , var initial; , var name; , var isPassed; , var num1, num2, num3;
  • No JavaScript reserved keywords
  • Meaningful names
  • Use camel case
  • Variable initialization: var age = 20; , var height = 5.5; , var initial = "K"; , var name = "Kamal"; , var isPassed = true;
  • Assigning values to variables: age = 20; , height = 5.5; , initial = "K"; , name = "Kamal"; , isPassed = true;
  • The const keyword was introduced in ES6 (ES2015) to create constants.
  • Example: const x = 5;
  • Constants cannot be changed: x = 10; would result in an error.
  • Constants must be initialized when declared: const x; would result in an error.

Using Variables

  • Reading and using variable values: var age = 20; , document.write(age); , age = 25; , document.write("Modified age = " + age);
  • JavaScript is a weakly typed language.

JavaScript Pop-up Boxes

  • Alert box: alert("This is an important message !");
  • Confirm box: var response = confirm("Press a button");
  • Prompt box: var name = prompt("enter your name", "Sir");
  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators

Control Structures

Selection/branching.

  • If-else statements: used to divide the algorithm execution path into branches based on conditions.
  • Conditions produce Boolean results.
  • If the mark is greater than or equals 50, display a message "Pass", else display a message "Fail".
  • Code: if (mark &gt;= 50) { document.write("Pass"); } else { document.write("Fail"); }

Repetition/Iteration/Looping

Studying that suits you.

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Description

Test your knowledge of variable initialization, assignment, and data types in JavaScript with this quiz. Practice understanding the output of different variable and data type operations in JavaScript.

More Quizzes Like This

JavaScript Data Types Quiz

JavaScript Data Types: Which Ones Are Not?

EnoughPorcupine avatar

JavaScript Variable Shadowing Quiz: Understand Scope and Hoisting

GoodlySaxophone avatar

জাভাস্ক্রিপ্ট ভেরিয়েবল এবং ডেটা টাইপ

ClearedCanyon avatar

জাভাস্ক্রিপ্টে ভেরিয়েবল এবং ডেটা টাইপ

Browser

Upgrade to continue

Today's Special Offer

Save an additional 20% with coupon: SAVE20

Upgrade to a paid plan to continue

Trusted by top students and educators worldwide

Stanford

We are constantly improving Quizgecko and would love to hear your feedback. You can also submit feature requests here: feature requests.

Create your free account

By continuing, you agree to Quizgecko's Terms of Service and Privacy Policy .

Data Types and Arithmetic Operators

Learn about the different data types and arithmetic operators available in JavaScript.

  • Introduction
  • Primitive types
  • Integers and arithmetic operators
  • Floating numbers
  • Infinity type

Get hands-on with 1200+ tech skills courses.

  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise

In this guide, we're going to talk about javascript data types. If you are new to javascript development or new to programming, then let's talk about what a data type is. Essentially it is how javascript categorizes all of our data points. If we have variables a data type is a way that javascript sees that type of variable so does it see a sentence or does it see a number. The reason why that's important (there are more categories than that). Those are just a few examples.

Imagine that you have a sentence of words that sentence can have certain types of functions called on them so you could capitalize on all the words if you tried to capitalize a number. Then an error is going to happen and it should because we need to know and we need to be able to use the right functions on the right type of data and that is what the data types allow us to do.

We are going to go through each one of the data types provided by javascript. I'm going to put a comment at the top for each one.

The first one, we're going to start alphabetically, is the Boolean data type.

Now Boolean can have two potential values. True and false.

I can declare some variables.

If I run this you can see it returns true.

medium

Now, this is not a name it's not a letter it's not a series of letters like our name variables are. These are just two values. True and false. And so those are the only two things that a boolean can be. So this would be something like saying is a user a paid user if you're building an application and it's a SASS product and you want to be able to see which of these users is paid and which ones are a free member. Well, you can in your data say this is a paid user it's true that they are paid and then when we get into conditionals we're going to talk about how we can leverage that to give our programs dynamic behavior. Right now just know that we have a boolean data type and it has two potential values true and false.

The next one we're going to talk about is the Null data type.

Now null can only have one value and that is null.

If I run this then it just prints out null.

Essentially what null is, is it's the absence of any kind of value.

The next one we're going to do you've kind of already seen but it's important to understand that it's different than null. So null means empty. So this would be something like say, that you had a registration page and you had some optional fields such as a Twitter user name or something like that. If a user decided not to fill that in then that value for that Twitter user name would just be null. It's our way of understanding that that variable or that value could be there. But in this case, it's just empty.

Moving down we're going to go to the next one which is undefined . We've seen that a few times and so undefined allows us to do is something that usually you're going to be using more with debugging because it's exactly what you get when something is simply declared. And it's not given a value.

and just say var not defined set it equal to, actually in this case I'm just we're not going to set it equal to anything because this is usually the way you're going to see this.

If I hit run you can see it's undefined. I didn't set it equal to undefined because by default when you simply declare a variable javascript is going to set it equal to undefined.

That's kind of an important thing to know because there are going to be many times when you're debugging your program and you'll think that you have access to some value or you think that you set the value only later on to find out. It comes back as undefined which means at some point the spot where the value got assigned got skipped or it never happened. Something like that so that's why that's important. And it's also nice because you can do things like check to see is this value defined yet or not. And there may seem to be some similarities between null and undefined but hopefully you can kind of see that subtle difference where null means that it is defined. It does have access to that variable but it just is empty. There's nothing there whereas with undefined what it means is it has not been assigned yet so it's not empty. There literally is no value that is there yet it needs to be assigned later.

Now the next one we're going to do may seem a little bit more practical and that is number . We've seen this before this is where we can do something like

This is just going to print out that value. 12 everything there works.

Now, this is where I want to take a little bit of a pause and talk about how javascript works with variables and data types much differently than many other programming languages. If you're coming to javascript from say, Java or C or C++ those are called statically typed languages. In those languages, what we just did here would not work.

The reason it would not work is that those languages typically require you to define what the data type is going to be. So the syntax would look something like this

And then in those cases those compilers when it's scanning the code and it comes to this age variable it says OK we can expect that age is going to be of the number data type. And here is the value. Well, javascript is similar to languages such as Ruby and Python where it actually skips that step. So you don't have to type that in the parser actually does that work for you. So in this case the interpreter is going to hit line 12. It's going to see var it's going to see age and then it's going to see that we assigned it. Now it does some checking and it checks to see what data type is 12 and when it sees that data type the data type for 12 is number it does the assignment and it forces that.

Javascript has some kind of side languages or some precompiler such as typescript that are very similar to javascript but they force you to put in the data types that are actually the reason why typescript is called typescript. A lot of it is a personal opinion.

There is a pretty big debate in the developer community on if statically or dynamically type languages are better people who believe in statically type languages, think that it's much better because it enforces this. Imagine a scenario with age where we think it's going to be a number but there are times where somebody types it in and it's a string.

Then if we ever tried to do any type of computation on that. Say we try to add age plus another number it's going to throw an error and the program is going to crash whereas if we had to enforce that. Then the program wouldn't have even compiled in the first place. Now some of that is kind of high level and starting to get a little bit more advanced so don't let that scare you off. I just want to give you a little bit of an idea of data types in javascript and how they work differently than in many other languages.

Continuing down the line. We have the

String data type now strings are what you're usually going to see used for words and sentences.

And this is using quotes. And then if I come here just like we've done before console.log this it's going to print out Kristine.

With the string data type we have a couple of different options we can do this. But we can also do something like this as well.

If I do name two. Notice that this is going to work exactly the same way. So we have name. And if I get a name two and run it it's going to print out both of these properly.

One of these had double quotation marks and one of them had single. For the most part in how you're going to be using javascript, it is not going to matter one way or the other. It starts to become more important when we talk about formatting output but we'll talk about that later on when we get into an entire module just dedicated to the string data type.

For right now just know that both of these when the javascript interpreter sees that it's going to recognize quotation marks and it's going to set that equal to the string data type.

The last one I'm going to talk about is a little bit more advanced and we're not going to go into a lot of detail on it mainly because you in building introductory type programs will never even touch the symbol data type. This is something that is brand new in ESX. So anything prior to that it will not know what a symbol is. Essentially what symbols do is they're kind of similar to strings except they have some very specific rules about them. They can not be changed. There can only be one of them. And so they're the closest thing that Javascript has to what's called an immutable type object. So when you create it then it is what it is you cannot change that value.

It's used primarily for working with objects which is what we're going to be talking about next. But they're more for advanced type features but I'm still going to show it to you just so you can see what all of the types of variables look like.

It's just going to print out an object symbol. Now you can pass a string in here so I could just pass foo

And one thing for new developers as you're reading documentation. You're going to see foo and bar used a lot. And I've actually had developers come up and ask what is special about foo and bar. As a side note, there is nothing special about them. They for some reason have just been used for decades in programming documentation and in explanations because it's a very quick way to just know a simple word to use it is literally the exact same.

I could type asdf or something like that it doesn't represent anything special. Whenever you see that on a stack overflow or some piece of documentation know that all they're doing is they just wanted a simple word to use. The only reason I wanted to bring it up is that I have been asked that by students multiple times. There's nothing special about it. It's just a piece of kind of programming lore in that sense.

If I hit run now. Now we have an object symbol

medium

but inside of it is the actual foo. If we're to use this in an object which we're going to talk about next then it's going to have unique representation which is going to be the symbol of foo.

That is the full set of data types in javascript. Once again that's boolean null undefined number string and symbol in the next guide we're going to talk about the very important type of component in javascript development that we're going to be using out this entire course so I wanted to dedicate an entire lesson to it. And that is the object.

  • Source code

devCamp does not support ancient browsers. Install a modern version for best experience.

Dipankar Paul's blog

Understanding javascript variables: declaration, scope, and data types.

Dipankar Paul's photo

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

EDUCBA

JavaScript Data Types

Updated February 21, 2023

JavaScript Data Types

Overview of JavaScript Data Types

While working with the computer, we found that many data types exist. Like number, String, Boolean, etc. But what’s the role of this data in a programming language? Of course, any programming language has predefined data types. For example, JavaScript also has its own set of data types.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

What is JavaScript?

JavaScript is a client-side scripting language. Java and JavaScript are two different programming languages; they are not similar. Before learning JavaScript, we recommend you to learn HTML and CSS first, as those are essential to learning web development technologies. JavaScript runs on the client-side of the browser. JavaScript is designed in a way to run on a browser. JavaScript is most important in front-end web development, making our web pages dynamic.

What does a dynamic webpage mean?

HTML is a structured language. It is static in nature. Everything you portray on the HTML shows the same output in the web browser. There was a need to get some events to happen on the client side. Like if the user clicks on a button that needs to happen something, make validation of forms to send correct data over the network. JavaScript is used to make web pages more interactive. It is possible to make web pages more user-friendly and easy to use. By making form validations and some events, we are indirectly reducing the load on the server, which helps the server to serve even faster to the request.

Declaring Variable in JavaScript

In JavaScript, we are declaring a variable as follows:

Look at the above code carefully. If you came from other programming languages like Java, you would see that we are not mentioning the type of variable we declare. And once the value is assigned to the variable, it cannot be changed.

In Java, you may do the following while declaring the variable.

//you cannot reassign value to the same variable

While declaring a variable, we tell the compiler that this variable is of type integer, But In JavaScript, the case is different. JavaScript is a dynamically typed language. That means you write keyword var and then the variable name. After that, the JavaScript engine internally changes the variable’s value to the correct data type.

Also, In JavaScript, we can reassign value to the variable even if we assigned t=value earlier to the same variable.

These features of JavaScript make it somewhat confusing to understand. But if you look closely, it’s very easy.

Data Types in Javascript

Two data types exist in javascript. one is primitive, and the other is user-defined.

There are a total of five data types in JavaScript as below:

The number is a primitive data type in JavaScript. In JavaScript for numbers, only one data type is there. Unlike other languages, JavaScript has no concept like float, decimal, or double. Ex.  

Above both variables number, even if variable m has a decimal point.

Both variables are addressed as numbers only.

The string is a primitive data type in JavaScript. The string is nothing but a collection of characters. Or some words. Look at the following example.

var str1 has value “Hello world”

you can write string value in single or double-quotes.

both are the same.

Sometimes, javascript doesn’t understand the quotes as they are nested. That time we are using the escape character to work it.

Let’s look at the following example. This shows we can use a single quote in double quotes and vice/Versa.

We need to use quotes carefully.

Boolean is a primitive data type in JavaScript. Boolean has two values, true and false. In JavaScript, we use Boolean values when there is a condition we want to apply. This is very useful when checking the condition while validating something with JavaScript. Ex:

Boolean is useful when we check whether the condition is true or false.

4. Undefined

Undefined is a primitive data type in JavaScript. Any variable in javascript which not have value. This means it is declared but not assigned with any value that variable has by default value undefined in JavaScript. A variable which not been assigned a value to the variable.

We will get the undefined value if we save this and open this in the browser console.

Write the following code in the console.

This will give undefined as an output.

Null is also a primitive data type in JavaScript. If we want a particular value intentionally empty, we can assign it the Null value. For example, we can say when some condition is we want to take value from the user at run time; then we can use Null data type.

Non-Primitive Data Types of JavaScript

Object, Array is the non-primitive data type. Finally, a symbol is a new data type introduced in  ECMAScript.

Object is the data type all the JavaScript is about.

We can define the object with object literal syntax. An object contains a pair of key-value pairs. Look at the following example.

An object contains multiple values.

Arrays are containers to store multiple values in a single variable.

In JavaScript array is referred to as an object. So, for example, if we type the following code in the browser console, we can get a type of Array as an object.

JavaScript data types are very important to understand. JavaScript is a loosely typed language. JavaScript intelligent engine covers the assigned value to the variable in an appropriate type. Therefore, while learning JavaScript, you should know data types.

Recommended Articles

This has been a guide to JavaScript Data Types. Here we have discussed the Overview of JavaScript Data Types and the Concept of Data Types. You may also look at the following article to learn more –

  • Encapsulation in JavaScript
  • Variables in JavaScript
  • TypeScript vs JavaScript
  • JavaScript Compilers

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy .

Forgot Password?

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Quiz

Explore 1000+ varieties of Mock tests View more

Submit Next Question

Early-Bird Offer: ENROLL NOW

quiz

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Data types in expressions in a paginated report (Report Builder)

  • 11 contributors

Data types represent different kinds of data in a paginated report so that it can be stored and processed efficiently. Typical data types include text (also known as strings), numbers with and without decimal places, dates and times, and images. Values in a report must be an Report Definition Language (RDL) data type. You can format a value according to your preference when you display it in a report. For example, a field that represents currency is stored in the report definition as a floating point number, but can be displayed in a variety of formats depending on the format property you choose.

For more information about display formats, see Formatting Report Items (Report Builder and SSRS) .

You can create and modify paginated report definition (.rdl) files in Microsoft Report Builder, Power BI Report Builder , and in Report Designer in SQL Server Data Tools.

Report Definition Language (RDL) Data Types and Common Language Runtime (CLR) Data Types

Values that are specified in an RDL file must be an RDL data type. When the report is compiled and processed, RDL data types are converted to CLR data types. The following table displays the conversion, which is marked Default:

RDL Type CLR Types
String Default: String

Chart, GUID, Timespan
Boolean Default: Boolean
Integer Default: Int64

Int16, Int32, Uint16, Uint64, Byte, Sbyte
DateTime Default: DateTime

DateTimeOffset
Float Default: Double

Single, Decimal
Binary Default: Byte[]
Variant Any of the above except Byte[]
VariantArray Array of Variant
Serializable Variant or types marked with Serializable or that implement ISerializable.

Understanding Data Types and Writing Expressions

It is important to understand data types when you write expressions to compare or combine values, for example, when you define group or filter expressions, or calculate aggregates. Comparisons and calculations are valid only between items of the same data type. If the data types do not match, you must explicitly convert the data type in the report item by using an expression.

The following list describes cases when you may need to convert data to a different data type:

Comparing the value of a report parameter of one data type to a dataset field of a different data type.

Writing filter expressions that compare values of different data types.

Writing sort expressions that combine fields of different data types.

Writing group expressions that combine fields of different data types.

Converting a value retrieved from the data source from one data type to a different data type.

Determining the Data Type of Report Data

To determine the data type of a report item, you can write an expression that returns its data type. For example, to show the data type for the field MyField , add the following expression to a table cell: =Fields!MyField.Value.GetType().ToString() . The result displays the CLR data type used to represent MyField , for example, System.String or System.DateTime .

Converting Dataset Fields to a Different Data Type

You can also convert dataset fields before you use them in a report. The following list describes ways that you can convert an existing dataset field:

Modify the dataset query to add a new query field with the converted data. For relational or multidimensional data sources, this uses data source resources to perform the conversion.

Create a calculated field based on an existing report dataset field by writing an expression that converts all the data in one result set column to a new column with a different data type. For example, the following expression converts the field Year from an integer value to a string value: =CStr(Fields!Year.Value) . For more information, see Add, Edit, Refresh Fields in the Report Data Pane (Report Builder and SSRS) .

Check whether the data processing extension you are using includes metadata for retrieving preformatted data. For example, a SQL Server Analysis Services MDX query includes a FORMATTED_VALUE extended property for cube values that have already been formatted when processing the cube. For more information, see Extended Field Properties for an Analysis Services Database (SSRS) .

Understanding Parameter Data Types

Report parameters must be one of five data types: Boolean, DateTime, Integer, Float, or Text (also known as String). When a dataset query includes query parameters, report parameters are automatically created and linked to the query parameters. The default data type for a report parameter is String. To change the default data type of a report parameter, select the correct value from the Data type drop-down list on the General page of the Report Parameter Properties dialog box.

Report parameters that are DateTime data types do not support milliseconds. Although you can create a parameter based on values that include milliseconds, you cannot select a value from an available values drop-down list that includes Date or Time values that include milliseconds.

Writing Expressions that Convert Data Types or Extract Parts of Data

When you combine text and dataset fields using the concatenation operator (&), the common language runtime (CLR) generally provides default formats. When you need to explicitly convert a dataset field or parameter to a specific data type, you must use a CLR method or a Visual Basic runtime library function to convert the data.

The following table shows examples of converting data types.

Type of conversion Example
DateTime to String
String to DateTime
String to DateTimeOffset
Extracting the Year



Boolean to Integer

-1 is True and 0 is False.
Boolean to Integer

1 is True and 0 is False.
Just the DateTime part of a DateTimeOffset value
Just the Offset part of a DateTimeOffset value

You can also use the Format function to control the display format for value. For more information, see Functions (Visual Basic) .

Advanced Examples

When you connect to a data source with a data provider that does not provide conversion support for all the data types on the data source, the default data type for unsupported data source types is String. The following examples provide solutions to specific data types that are returned as a string.

Concatenating a String and a CLR DateTimeOffset Data Type

For most data types, the CLR provides default conversions so that you can concatenate values that are different data types into one string by using the & operator. For example, the following expression concatenates the text "The date and time are: " with a dataset field StartDate, which is a DateTime value: ="The date and time are: " & Fields!StartDate.Value .

For some data types, you may need to include the ToString function. For example, the following expression shows the same example using the CLR data type DateTimeOffset , which include the date, the time, and a time-zone offset relative to the UTC time zone: ="The time is: " & Fields!StartDate.Value.ToString() .

Converting a String Data Type to a CLR DateTime Data Type

If a data processing extension does not support all data types defined on a data source, the data may be retrieved as text. For example, a datetimeoffset(7) data type value may be retrieved as a String data type. In Perth, Australia, the string value for July 1, 2008, at 6:05:07.9999999 A.M. would resemble:

2008-07-01 06:05:07.9999999 +08:00

This example shows the date (July 1, 2008), followed by the time to a 7-digit precision (6:05:07.9999999 A.M.), followed by a UTC time zone offset in hours and minutes (plus 8 hours, 0 minutes). For the following examples, this value has been placed in a String field called MyDateTime.Value .

You can use one of the following strategies to convert this data to one or more CLR values:

In a text box, use an expression to extract parts of the string. For example:

The following expression extracts just the hour part of the UTC time zone offset and converts it to minutes: =CInt(Fields!MyDateTime.Value.Substring(Fields!MyDateTime.Value.Length-5,2)) * 60

The result is 480 .

The following expression converts the string to a date and time value: =DateTime.Parse(Fields!MyDateTime.Value)

If the MyDateTime.Value string has a UTC offset, the DateTime.Parse function first adjusts for the UTC offset (7 A.M. - [ +08:00 ] to the UTC time of 11 P.M. the night before). The DateTime.Parse function then applies the local report server UTC offset and, if necessary, adjusts the time again for Daylight Saving Time. For example, in Redmond, Washington, the local time offset adjusted for Daylight Saving Time is [-07:00] , or 7 hours earlier than 11 PM. The result is the following DateTime value: 2007-07-06 04:07:07 PM (July 6, 2007 at 4:07 P.M).

For more information about converting strings to DateTime data types, see Parsing Date and Time Strings , Formatting Date and Time for a Specific Culture , and Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo .

Add a new calculated field to the report dataset that uses an expression to extract parts of the string. For more information, see Add, Edit, Refresh Fields in the Report Data Pane (Report Builder and SSRS) .

Change the report dataset query to use Transact-SQL functions to extract the date and time values independently to create separate columns. The following example shows how to use the function DatePart to add a column for the year and a column for the UTC time zone converted to minutes:

MyDateTime,

DATEPART(year, MyDateTime) AS Year,

DATEPART(tz, MyDateTime) AS OffsetinMinutes

FROM MyDates

The result set has three columns. The first column is the date and time, the second column is the year, and the third column is the UTC offset in minutes. The following row shows example data:

2008-07-01 06:05:07 2008 480

For more information about SQL Server database data types, see Data Types (Transact-SQL) , and Date and Time Data Types and Functions (Transact-SQL) .

For more information about SQL Server Analysis Services data types, see Data Types in Analysis Services .

Formatting Report Items (Report Builder and SSRS)

Was this page helpful?

Additional resources

  • How it works
  • Homework answers

Physics help

Answer to Question #312577 in HTML/JavaScript Web Application for dhanush

Write a JavaScript and plot the data given in the

excel sheet like below

Need a fast expert's response?

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS !

Leave a comment

Ask your question, related questions.

  • 1. Cumulative Sumgiven an array integers, write a JS program to get the cumulative sum of the items in
  • 2. Magical IndicesInputThe first line of input contains an arrayThe second line of input contains a num
  • 3. Trekking kit program in JS is giving only one output correctly
  • 4. product of array itemsgiven an array integers, write a JS program to get the product of the given in
  • 5. Create and test an HTML document that has at least a half-page oftext and a small box of text embedd
  • 6. In a new index.html file display three images (that you would be legally allowed to use for a commer
  • 7. The goal of this coding exam is to quickly get you off the ground with the array method every ()Ther
  • Programming
  • Engineering

10 years of AssignmentExpert

Who Can Help Me with My Assignment

There are three certainties in this world: Death, Taxes and Homework Assignments. No matter where you study, and no matter…

How to finish assignment

How to Finish Assignments When You Can’t

Crunch time is coming, deadlines need to be met, essays need to be submitted, and tests should be studied for.…

Math Exams Study

How to Effectively Study for a Math Test

Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…

IMAGES

  1. JavaScript Series Part 3: Ultimate Guide to Data Types in JavaScript

    data type report javascript assignment expert

  2. JavaScript Data Types

    data type report javascript assignment expert

  3. 33 Primitive Data Type Javascript

    data type report javascript assignment expert

  4. SOLUTION: Data Types In Javascript

    data type report javascript assignment expert

  5. 35 w3schools javascript data types

    data type report javascript assignment expert

  6. Data Types in JavaScript

    data type report javascript assignment expert

VIDEO

  1. Javascript Datatypes

  2. JavaScript for Testers: Part 3

  3. 08. Data Types in JavaScript

  4. 9- Java Script Free Course : Data Types

  5. 6- JavaScript Tutorial for Beginners

  6. Javascript Data Types

COMMENTS

  1. Answer in Web Application for king #303194

    Answer to Question #303194 in HTML/JavaScript Web Application for king Answers > Programming & Computer Science > HTML/JavaScript Web Application Question #303194 Date Type Report given an array myArray write a JS program to find the count of number,object,string,boolean. data values in the array sample input1 [1, '2', true, {'a':'b'}, false]

  2. Answer in Web Application for king #303270

    Answer to Question #303270 in HTML/JavaScript Web Application for king Answers > Programming & Computer Science > HTML/JavaScript Web Application

  3. JavaScript Assignment

    Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  4. Assignment (=)

    The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

  5. JavaScript data types and data structures

    JavaScript data types and data structures Programming languages all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in JavaScript and what properties they have. These can be used to build other data structures.

  6. JavaScript Data Types

    JavaScript Types are Dynamic JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

  7. Javascript Assignment Operators (with Examples)

    In this tutorial, you will learn about all the different assignment operators in javascript and how to use them in javascript.

  8. JavaScript Basics: Data Types

    Data Types Variables can store many different types of values, like numbers and text. These various types of values are known as the data type. Data types are an important part of software development because it helps developers make decisions on how the code should be written and how the software should run.

  9. JavaScript Data Types (with Examples)

    Data types represent the different kinds of values we can use in JavaScript. In this tutorial, you will learn about the various data types available in JavaScript with the help of examples.

  10. JavaScript Variables and Assignment Operators

    In this beginning-level project you will work with JavaScript variables and assignment operators by writing and testing JavaScript code using the Notepad++ text editor and the Chrome browser. Since variables are used as containers to hold values in JavaScript, knowing how to use them is an essential skill for a JavaScript programmer.

  11. Variables and Datatypes in JavaScript

    Variables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand.

  12. JavaScript: Variables, Data Types and Operators

    A data type is the type of content of a variable. You already know one: string. A string basically is a text, a string of characters put together. There are other data types as well. You can, for example, use numbers as variables: var number = 5; console.log(number); The variable number here has the content 5.

  13. Exploring the Various Data Types in JavaScript: From Primitives to Objects

    The main data types in JavaScript include: Primitive data types: These are the basic data types that include numbers, strings, booleans, and special values like null and undefined. Data Type. Description. String. A string is a collection of alphanumeric characters. Number. Numbers are for numbers. We can't put a letter on here.

  14. JavaScript Variables and Data Types Quiz

    Test your knowledge of variable initialization, assignment, and data types in JavaScript with this quiz. Practice understanding the output of different variable and data type operations in JavaScript.

  15. Data Types and Arithmetic Operators

    Learn about the different data types and arithmetic operators available in JavaScript.

  16. Comprehensive List of JavaScript Data Types

    In this guide, we're going to talk about javascript data types. If you are new to javascript development or new to programming, then let's talk about what a data type is. Essentially it is how javascript categorizes all of our data points. If we have variables a data type is a way that javascript sees that type of variable so does it see a sentence or does it see a number. The reason why that ...

  17. Understanding JavaScript Variables: Declaration, Scope, and Data Types

    JavaScript supports various data types for variables, including numbers, strings, booleans, objects, and symbols. Variables can be assigned values using the assignment operator (=) and updated as needed.

  18. Answer in Web Application for hemanth #170566

    Question #170566. inputString, separator and replaceString as inputs. Write a JS program to split the. inputString with the given separator and replace strings in the resultant array with the replaceString whose length is greater than 7.

  19. Destructuring assignment

    Destructuring assignment The two most used data structures in JavaScript are Object and Array.

  20. JavaScript Data Types

    Guide to JavaScript Data Types. Here we discuss Overview of JavaScript Data, What is JavaScript and Data Types in Javascript.

  21. Answer in Web Application for king #303239

    Answer to Question #303239 in HTML/JavaScript Web Application for king Answers > Programming & Computer Science > HTML/JavaScript Web Application Question #303239 Cumulative Sum given an array integers, write a JS program to get the cumulative sum of the items in the array sample input1 [1, 10, 100, 1000] sample output1 [1, 11, 111, 1111] "use ...

  22. Data types in expressions in a paginated report (Report Builder)

    Data types represent different kinds of data in a paginated report so that it can be stored and processed efficiently. Typical data types include text (also known as strings), numbers with and without decimal places, dates and times, and images. Values in a report must be an Report Definition Language (RDL) data type.

  23. Answer in Web Application for dhanush #312577

    Question #312577. Write a JavaScript and plot the data given in the. excel sheet like below.