Google News
logo
CoffeeScript Interview Questions
The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself.
outer = 1
changeNumbers = ->
  inner = -1
  outer = 10
inner = changeNumbers()​
var changeNumbers, inner, outer;
​
outer = 1;
​
changeNumbers = function() {
  var inner;
  inner = -1;
  return outer = 10;
};
​
inner = changeNumbers();​
Notice how all of the variable declarations have been pushed up to the top of the closest scope, the first time they appear. outer is not redeclared within the inner function, because it’s already in scope; inner within the function, on the other hand, should not be able to change the value of the external variable of the same name, and therefore has a declaration of its own.
if/else statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, multi-line conditionals are delimited by indentation. There’s also a handy postfix form, with the if or unless at the end.
 
CoffeeScript can compile if statements into JavaScript expressions, using the ternary operator when possible, and closure wrapping otherwise. There is no explicit ternary statement in CoffeeScript — you simply use a regular if statement on a single line.
mood = greatlyImproved if singing
​
if happy and knowsIt
  clapsHands()
  chaChaCha()
else
  showIt()
​
date = if friday then sue else jill
var date, mood;
​
if (singing) {
  mood = greatlyImproved;
}
​
if (happy && knowsIt) {
  clapsHands();
  chaChaCha();
} else {
  showIt();
}
​
date = friday ? sue : jill;
The CoffeeScript provides a feature known as splat which is used to pass multiple arguments to a function.
 
We can use splats in functions by placing three dots (...) after the variable name.
 
Example :
indian_team = (first, second, others...) ->  
  Captain = first  
  WiseCaptain = second  
  team  = others  
  console.log "Captain: " +Captain  
  console.log "Wise captain: " +WiseCaptain  
  console.log "Other team members: " +team  
  
#Passing 4 arguments  
console.log "############## Four Players ############"  
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma"  
  
#Passing 6 arguments  
console.log "############## Six Players ############"  
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan"  
    
#Passing full squad  
console.log "############## Full squad #############"  
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"  
Explanation of the above example :
 
In the above case of spats, multiple arguments were being passed to the function. By placing three dots after the argument list of the function indian_team. In the first pass we have passed four arguments to the function, in the second pass we have passed six arguments to the function, and in the last pass, we had passed the names of the full squad to the function.
Most of the loops you’ll write in CoffeeScript will be comprehensions over arrays, objects, and ranges. Comprehensions replace (and compile into) for loops, with optional guard clauses and the value of the current array index. Unlike for loops, array comprehensions are expressions, and can be returned and assigned.
# Eat lunch.
eat = (food) -> "#{food} eaten."
eat food for food in ['toast', 'cheese', 'wine']
​
# Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu = (i, dish) -> "Menu Item #{i}: #{dish}" 
menu i + 1, dish for dish, i in courses
​
# Health conscious meal.
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
// Eat lunch.
var courses, dish, eat, food, foods, i, j, k, l, len, len1, len2, menu, ref;
​
eat = function(food) {
  return `${food} eaten.`;
};
​
ref = ['toast', 'cheese', 'wine'];
for (j = 0, len = ref.length; j < len; j++) {
  food = ref[j];
  eat(food);
}
​
// Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'];
​
menu = function(i, dish) {
  return `Menu Item ${i}: ${dish}`;
};
​
for (i = k = 0, len1 = courses.length; k < len1; i = ++k) {
  dish = courses[i];
  menu(i + 1, dish);
}
​
// Health conscious meal.
foods = ['broccoli', 'spinach', 'chocolate'];
​
for (l = 0, len2 = foods.length; l < len2; l++) {
  food = foods[l];
  if (food !== 'chocolate') {
    eat(food);
  }
}​

Comprehensions should be able to handle most places where you otherwise would use a loop, each/forEach, map, or select/filter, for example :
shortNames = (name for name in list when name.length < 5)
If you know the start and end of your loop, or would like to step through in fixed-size increments, you can use a range to specify the start and end of your comprehension.
The splats with tailing argument refer to the argument placed after the splat argument.
 
Example :
indian_team = (first, second, others...., last) ->  
  Captain = first  
  WiseCaptain = second  
  team  = others  
  Wicketkeeper =last  
  console.log "Captain: " +Captain  
  console.log "Wise captain: " +WiseCaptain  
  console.log "Wicket keeper is:"+last  
  console.log "Other team members: " +team    
    
squad = [  
   "Mahendra Singh Dhoni"  
   "Virat Kohli"  
   "Shikhar Dhawan"  
   "Rohit Sharma"     
   "Gurkeerat Singh Mann"  
   "Rishi Dhawan"  
   "R Ashwin"  
   "Ravindra Jadeja"  
   "Axar Patel"  
   "Jasprit Bumrah"  
   "Umesh Yadav"  
   "Harbhajan Singh"  
   "Ashish Nehra"  
   "Hardik Pandya"  
   "Suresh Raina"  
   "Yuvraj Singh"  
   "Ajinkya Rahane"  
 ]​
  
In the above example of using tailing with splats, we have placed an additional argument to the argument list of the indian_team function.
We can use the javascript library in CoffeeScript code. Hence we can use all the methods of math object in javascript.
 
Some math function present in the math object :
 
* abs() : This function returns the absolute value of a number.

*
acos() : This function returns arccosine (in radians) of a number.

*
asin() : This function returns arcsine (in radians) of a number.

*
atan() : This function returns arctangent (in radians) of a number.

*
atan2() : This function returns arctangent of the quotient of its arguments.

*
ceil() : This function returns the smallest integer greater than or equal to the given number.

*
cos() : This function returns the cosin of the given number.

*
exp() : This function returns EN, Where N is the argument, and E is the Euler's constant, the base of the natural logarithm.

*
floor() : This function returns the largest integer less than equal to the number.

*
log() : This function returns natural logarithm (base E) of a number.

*
max() : This function returns largest of zero or more numbers.

*
min() : This function returns the smallest of zero or more numbers.

*
pow() : This function returns the base exponent of the given number.

*
random() : This function returns the pseudo-random number between 0 and 1.

*
round() : This function returns the value of the number rounded to the nearest integer.

*
sin() : This function returns the sine of the given number.

*
sqrt() : This function returns the square root of the specified number.

*
tan() : This function returns the tangent of the specified number.
Clone function is useful in creating completly new object by :

* Creating a new object as the source object.
* Copying all attributes from the source object to the new object.
Ranges can also be used to extract slices of arrays. With two dots (3..6), the range is inclusive (3, 4, 5, 6); with three dots (3...6), the range excludes the end (3, 4, 5). Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
​
start   = numbers[0..2]
​
middle  = numbers[3...-2]
​
end     = numbers[-2..]
​
copy    = numbers[..]​
var copy, end, middle, numbers, start;
​
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
​
start = numbers.slice(0, 3);
​
middle = numbers.slice(3, -2);
​
end = numbers.slice(-2);
​
copy = numbers.slice(0);​
​
The same syntax can be used with assignment to replace a segment of an array with new values, splicing it.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
​
numbers[3..6] = [-3, -4, -5, -6]​
var numbers, ref,
  splice = [].splice;
​
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
​
splice.apply(numbers, [3, 4].concat(ref = [-3, -4, -5, -6])), ref;

Note that JavaScript strings are immutable, and can’t be spliced.

Because the == operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, CoffeeScript compiles == into ===, and != into !==. In addition, is compiles into ===, and isnt into !==.
 
You can use not as an alias for !.
 
For logic, and compiles to &&, and or into ||.
 
Instead of a newline or semicolon, then can be used to separate conditions from expressions, in while, if/else, and switch/when statements.
 
As in YAML, on and yes are the same as boolean true, while off and no are boolean false.
 
unless can be used as the inverse of if.
 
As a shortcut for this.property, you can use @property.
 
You can use in to test for array presence, and of to test for JavaScript object-key presence.
 
In a for loop, from compiles to the ES2015 of. (Yes, it’s unfortunate; the CoffeeScript of predates the ES2015 of.)
 
To simplify math expressions, ** can be used for exponentiation and // performs floor division. % works just like in JavaScript, while %% provides “dividend dependent modulo”:
-7 % 5 == -2 # The remainder of 7 / 5
-7 %% 5 == 3 # n %% 5 is always between 0 and 4
​
tabs.selectTabAtIndex((tabs.currentIndex - count) %% tabs.length)

 

var modulo = function(a, b) { return (+a % (b = +b) + b) % b; };
​
-7 % 5 === -2; // The remainder of 7 / 5
​
modulo(-7, 5) === 3; // n %% 5 is always between 0 and 4
​
tabs.selectTabAtIndex(modulo(tabs.currentIndex - count, tabs.length));​

All together now : 

CoffeeScript JavaScript
is ===
isnt !==
not !
and &&
or ||
true, yes, on true
false, no, off false
@, this this
a in b [].indexOf.call(b, a) >= 0
a of b a in b
for a from b for (a of b)
a ** b a ** b
a // b Math.floor(a / b)
a %% b (a % b + b) % b
ES2017’s async functions are supported through the await keyword. Like with generators, there’s no need for an async keyword; an async function in CoffeeScript is simply a function that awaits.
 
Similar to how yield return forces a generator, await return may be used to force a function to be async.
# Your browser must support async/await and speech synthesis
# to run this example.
sleep = (ms) ->
  new Promise (resolve) ->
    window.setTimeout resolve, ms
​
say = (text) ->
  window.speechSynthesis.cancel()
  window.speechSynthesis.speak new SpeechSynthesisUtterance text
​
countdown = (seconds) ->
  for i in [seconds..1]
    say i
    await sleep 1000 # wait one second
  say "Blastoff!"
​
countdown 3​
// Your browser must support async/await and speech synthesis
// to run this example.
var countdown, say, sleep;
​
sleep = function(ms) {
  return new Promise(function(resolve) {
    return window.setTimeout(resolve, ms);
  });
};
​
say = function(text) {
  window.speechSynthesis.cancel();
  return window.speechSynthesis.speak(new SpeechSynthesisUtterance(text));
};
​
countdown = async function(seconds) {
  var i, j, ref;
  for (i = j = ref = seconds; (ref <= 1 ? j <= 1 : j >= 1); i = ref <= 1 ? ++j : --j) {
    say(i);
    await sleep(1000); // wait one second
  }
  return say("Blastoff!");
};
​
countdown(3);