What is the difference between Array/array, Object/Object, etc?

Asked

Viewed 760 times

1

I’m right at the beginning of my programming study and I’m not quite clear on these types with the first letter capitalized in Javascript, as Number, Array, Object, etc..

let a = Array
let b = [1, 2]
let c = Object
let d = {a: 1, b: 2}

Because uppercase fonts are functions?

2 answers

1


The Javascript language offers some variavies (reserved words) with pre-defined functionality. In this case of your question we are talking about primitive types, that is to say the building blocks of the language. These types are: Boolean, Number, String, Symbol, Object.

When do you ask "Because uppercase fonts are functions?" - the answer is: because language is made like this.

You can use these guys as functions:

Boolean(123) // dá true
Boolean(0) // dá false

But you can also use as constructors to get objects, and then you have to see the result as an object that can expose properties:

const zero = new Boolean(0);
console.log(!!zero); // dá true porque um objeto valida como true quando convertido em Boolean
console.log(zero.valueOf()); // dá false, o valor booleano de "0"
  • It was this second code I didn’t understand, with this new operator.

  • @thar93 great that my answer helped to understand better.

0

Javascript is a language case sensitive, that is, differentiates upper and lower case letters (such as Java, PHP and others).

A few words, like Array and Object are words of internal language functions (see reserved words), and begin with uppercase letters by the language syntax itself. Hence the word array can be just any variable - in the same way as object.

You can even use reserved words as variables, but this should never be done because you will change their type and function, and this will cause error if you need to use the native word-related function:

let Number = "texto"; // Number é uma string qualquer
console.log(Number);
let numero = Number("3"); // aqui a função Number() dá erro pq você declarou como string antes
console.log(numero);

In the above example I ubverti the function Number turning it into a string, resulting in line error let numero = Number("3");.

In the example below, I didn’t touch the word Number (declared the first variable with lowercase "n") and the native function was not changed and worked correctly:

let number = "texto"; // number é uma string qualquer
console.log(number);
let numero = Number("3");
console.log(numero);

In short, the problem is not so much whether a word starts with uppercase or lowercase letter, it is in you know the syntax of the language and differentiate when one represents a function, property or method (whether starting with uppercase or lowercase letter)and when a word can be just any word it can be used as any variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.