The general forms, function foo () {}
and var bar = function () {};
have one important difference from const foobar = () => {};
, that is, the latter does not have a this
context object, and has no arguments
object.
It will be a little while before any of this is covered so put this in the back of your mind, for now. Bottom line, arrow notation is not a replacement for general function notation, but a labor saving device when applicable.
const
makes a variable protected. It cannot be overwritten or have its datatype changed.
Eg.
const foo = () => {};
foo = x => x ** 2;
console.log(foo(4));
output
SyntaxError: Assignment to constant variable: foo at 3:0.
const foo = x => x ** 2;
console.log(foo(4));
output
16
const
only applies to the name and type of data structures such as arrays and objects. These are reference objects that are treated dynamically permitting changes in the data points and the object length.
Eg.
const myArray = [];
myArray.push('foo', 'bar');
console.log(myArray); // ['foo', 'bar']
myArray.splice(1,0,'foobar');
console.log(myArray); // [ 'foo', 'foobar', 'bar' ]
Notice that we are able to modify the data, but if we try to reassign to the myArray
variable it will throw and error.
The method covered above is not likely covered in this course, so set it on a back burner. At some point we will be covering the push
, pop
, unshift
and shift
array methods, of which splice
is similar but able to insert an element at any index, or remove an element at any index.
You will learn eventually that pop
, shift
and splice
can be assigned to a variable or used in an expression once removed from the array.
let temp = myArray.splice(1,1);
console.log(temp); // [ 'foobar' ]
console.log(temp[0]); // foobar
temp = myArray.pop();
console.log(temp); // bar
temp = myArray.shift();
console.log(temp); // foo
Again, this is back-burner stuff but will surface eventually in your study of the language. Don’t let it segue you from the track path, but when the subject comes up. spend some time with it.