In JavaScript, the response to 1 + 1
can be either 2
or 11
depending on the data type. Understanding this requires
knowledge of the Seven basic data types or also called primitives in JavaScript:
String, Number, Boolean, Null, Undefined, Symbol, and BigInt.
String
Strings represent textual data in JavaScript and are created by enclosing text within quotation marks. You can use either single quotes (”) or double quotes (""). The choice between them is a matter of personal preference. For example:
Get started with JavaScript essentials: discover basic data types such as String, Number, and Boolean, and how they affect your code. Learn about semicolons and their role in code clarity, and understand how to use comments to document your work. Explore the browser console for running and debugging JavaScript, and see how to link JavaScript files to HTML using the
Strings can also include apostrophes by adding a backslash \
before the apostrophe or by using backticks
“. For
example:
Strings can be concatenated using the +
operator. For example:
So, that’s why 1
+ 1
can be 11
in JavaScript.
Number
Numbers represent numerical data, you create numbers by writing the number directly.
In JavaScript, numbers behave like they do in mathematics. For example:
Boolean
Boolean can only be true
or false
and are used for logical operations. For example:
Null and Undefined
Null and undefined both represent the absence of value. undefined
typically means a variable has been declared but not
assigned a value. null
is an assignment value that means no value or no object. For example:
Symbol
Symbol is a unique and immutable data type introduced in ES6. Each new Symbol value is completely unique. For example:
Symbols are rarely used and are meant for very unique cases that you won’t encounter often. You can read more about symbols.
BigInt
BigInt stands for Big Integer, allows you to represent integers larger than 2^53 - 1, which is the limit for Number. For example:
Remember that BigInt is not often used unless you work with very large numbers. You can read more about symbols.