In this lesson, we'll get an introduction to one of the most core and fundamental coding langauges, JavaScript. We'll practice implementing some JS code. We'll discuss JS data types and their usage.
- Learn about what JavaScript is
- Execute some JavaScript code
- Learn JavaScript Data Types
Wikipedia: JavaScript, often abbreviated as JS, is a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a language that is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm.
Mozilla: JavaScript (JS) is a lightweight interpreted or JIT-compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it. JavaScript is a prototype-based, multi-paradigm, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.
The latest ECMAScript standard defines seven data types:
- Number
- String
- Boolean
- Null
- Undefined
- Symbol
- Object
In other languages, numbers are divided into two classes or objects:
-
Integers
..., -1,0, 2, 3, 4, 5, ...
-
Floats (or Decimal numbers)
2.718, 3.14, .5, .25, etc
All numbers in JavaScript are "double-precision 64-bit format IEEE 754 values" - read this as "There's really no such thing as an integer in JavaScript."
Operators are used to work with data in JavaScript. The standard arithmetic operators (that you've been learning since grade school) are supported. This includes addition, subtraction, modulus (or remainder) arithmetic and so forth. Check it out:
1 + 2
=> 3
2 - 5
=> -3
5 / 2
=> 2.5
6 * 2
=> 12
JavaScript can be a little cheap with the number of operations it allows you to do. For example, how is someone supposed to square a number or cube a number easily? Luckily there is a special Math
object with some very useful methods.
- Taking a number to some power? Then just use
Math.pow
...
// 3^2 becomes
Math.pow(3,2)
=> 9
// 2^4 becomes
Math.pow(2,4)
=> 16
- Taking a square root? Try
Math.sqrt
...
// √4 becomes
Math.sqrt(4)
=> 2
- Need a random number? Then use
Math.random
...
// The following only returns a random decimal
Math.random()
=> .229375290430
/**
The following will return a
random number between 0 and 10
*/
Math.random()*10
- Since Numbers can be Floats or Integers we often want to get rid of remaining decimal places, which can be done using
Math.floor
,Math.ceil
, orMath.round
...
// round down to the nearest integer
Math.floor(3.14)
=> 3
Math.floor(3.9999)
=> 3
// round up to the nearest integer
Math.ceil(3.14)
=> 4
Math.ceil(3.9999)
=> 4
// Mathematically round to the nearest integer
Math.round(3.14)
=> 3
Math.round(3.9999)
=> 4
Strings are collections of letters and symbols known as characters, and we use them to deal with words and text in JavaScript. Strings are just another type of value in Javascript.
There are three ways to write a string in JavaScript.
- Surround a word or phrase with double quotes,
"like this"
- Surround a word or phrase with single quotes,
'like this'
- Surround a word or phrase with backticks (below the tilde key),
`like this`
This last version, with backticks, allows you to inject javascript into a string using something called "string interpolation." (which we'll get to shortly).
To find the length of a string, access its length
property:
'hello'.length;
=> 5
There's our first brush with JavaScript objects! Did I mention that you can use strings like objects, too?
Strings have other methods as well that allow you to manipulate the string and access information about the string:
'hello'.charAt(0);
=> "h"
'hello, world'.replace('hello', 'goodbye');
=> "goodbye, world"
'hello'.toUpperCase();
=> "HELLO"
Types of values like Number
or String
are not very useful without being able to form Expressions or Combinations.
Try your favorite number operators as expressions:
1 + 1
=> 2
2 - 1
=> 1
You can also create expressions with strings using the addition operator:
'Hello, ' + 'world!'
=> "Hello, world!"
This is called String Concatentation.
Note: the 'plus' binary operator is said to be "overloaded"— meaning that it behaves differently depending on what's on either side of it. Consider the following expressions. What do they output, and why?
1 + 2 + '3'
vs'1' + 2 + 3
You can convert a string to an integer using the built-in parseInt()
function. This takes the base for the conversion as an optional second argument, which you should always provide:
parseInt('123', 10);
=> 123
parseInt('010', 10);
=> 10
This will be important later when we're taking user input from the web and using it on our server or in our browser to do some type of numeric calculation.
Similarly, you can parse floating point numbers using the built-in parseFloat()
function which uses base 10 always unlike its parseInt()
cousin.
parseFloat('11.2');
=> 11.2
You can also use the unary +
operator to convert values to numbers:
+"42";
=> 42
Variables are used to store data types into the memory of the computer so that they can be referenced later.
New variables in JavaScript are declared using the let
or const
` keywords.
If you declare a variable without assigning any value to it, its type is undefined
.
let a;
=> undefined
So let's try assigning a value to variable:
const name = 'Alex';
=> undefined
name
=> "Alex"
Having made some expressions it becomes evident we want to store these values.
const myNumber = 1;
// or also
const myString = 'Greetings y\'all!'
The main notes to make here is that these variables should always have the const
, or let
keyword and use camelCase
. Also remember to escape strings using \'
.
Values are assigned using =
, and there are also compound assignment statements such as +=
and -=
:
let x = 1;
=> 1
x += 5
=> 6
You can use ++
and --
to increment and decrement, respectively. These can be used as prefix or postfix operators.
In Javascript we just discussed two types of values we can use. We call these values objects, which for now just means that in addition to storing some data you also get to use some helpful methods when you are working with them.
- If you want to turn a number into a string you can use a helpful method called
toString
.
(1).toString()
=> "1"
/**
be careful though,
since numbers can be floats
javascript might
misunderstand you.
*/
1.toString()
=> Float Error
// but the following works
1..toString()
The difference between let
and const
are the with let, variables can be reassigned, wheras with const, they cannot.
Try:
let myNumber = 23;
myNumber = 5;
Now try:
const myNumber = 23;
myNumber = 5;
Discuss: Why might you want to use const instead of let?
When you wrap a string with backticks, you can "inject" JavaScript into that string, using the following syntax:
const firstName = "Brian"
const age = 33
`My name is ${firstName} and on my next birthday, I will be ${age + 1} years old.`
As you can see, string interpolation provides an easy way to inject variables or do basic math or logic functions dynamically.
The parseInt()
and parseFloat()
functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN
if there is any invalid character in it.
A special value called NaN
(short for "Not a Number") is returned if the string is non-numeric:
parseInt('hello', 10);
=> NaN
NaN
is toxic: if you provide it as an input to any mathematical operation the result will also be NaN
:
NaN + 5;
=> NaN
You can test for NaN
using the built-in isNaN()
function:
isNaN(NaN);
=> true
JavaScript's numeric operators are +
, -
, *
, /
and %
and all work as you expect and should have practiced during your pre-work.
Boolean represents a logical entity and can have two values: true
, and false
.
All of the following become false when converted to a Boolean
false
0
''
(empty string)NaN
null
undefined
All other values become true when converted to a Boolean
There is a simple way of verifying the truthiness or falsiness of a value. When you add !
in front of a value, the returned value will be the inverse of the value in a boolean. So if you add two !
then you'll get the boolean value of the original one:
!!1
//=> true
!!0
//=> false
!!-1
//=> true
!![]
//=> true
!!{}
//=> true
!!null
//=> false
!!""
//=> false
Logical operators will always return a boolean value true
or false
.
There are two "binary" operators that require two values:
- AND, denoted
&&
- OR, denoted
||
A third "unary" operator requires only one value:
- NOT, denoted
!
The &&
operator requires both left and right values to be true
in order to return true
:
true && true
//=> true
Any other combination is false.
true && false
//=> false
false && false
//=> false
The ||
operator requires just one of the left or right values to be true
in order to return true.
true || false
//=> true
false || true
//=> true
false || false
//=> false
Only false || false
will return false
The !
takes a value and returns the opposite boolean value, i.e.
!true
//=> false
The value null represents the intentional absence of a value.
let trigger = null;
A variable that has not been assigned a value has the value undefined.
let count;
In this lesson, we learned about what JavaScript is. We also learned about JavaScript data types and how to use some of them.