Good afternoon, I recently started learning javascript, in one of those I came across such code:

function hardWork() { for (i = 0; i < 1e8; i++) hardWork[i % 2] = i; } 

In principle, I understand what this function does, but I have never seen such an expression hardWork[i % 2] = i; , I will be grateful if someone explains what the square brackets are for here

  • And why such a f-tion? Apparently she has one goal - to hang the PC. - nick_n_a
  • @nick_n_a, well, well, the name of the function seems to hint. - Xander

1 answer 1

Square brackets are used to get / add a parameter to an object.

Usually brackets are used if the parameter name is not known in advance, or the parameter is not a valid js identifier (for example, contains spaces or special characters).

Note:

 var foo = {'a': 1, 'b': 2} //получить 'a' var a = foo['a'] // аналочино a = foo.a //добавить новое поле 'c' равное 3 foo['c'] = 3 // аналогично foo.c = 3 //добавить новое поле (название которого хранится в переменной) var param_name = 'my cool param' foo[ param_name ] = 'some value' // аналога с использованием точки нет. 

In js, functions are objects of type Function . Therefore, in them (as in all other objects) you can add new properties or change the values ​​of existing ones (although not all, for example, name and length cannot be changed).

This can be used for example to cache the result of a function:

 function fib( n ){ //функция считающая н-ое число Фибоначчи // (0, 1, 1, 2, 3, 5, 8, ... (n-2)+(n-1) ) console.log( 'calc fib of', n ) if( n == 1 ) return 1; if( n == 0 ) return 0 if( !( n in fib ) ) fib[ n ] = fib( n - 1 ) + fib( n - 2 ); return fib[ n ] } fib( 3 ) /* напечатает calc fib of 3 calc fib of 2 calc fib of 1 calc fib of 0 calc fib of 1 т.е. функция выполнилась 5 раз */ // повторный вызов fib( 3 ) /* напечатает calc fib of 3 функция выполилась только 1 раз (не пришлось расчитывать всё заново) */