diff --git a/.bookignore b/.bookignore new file mode 100644 index 0000000..47f6177 --- /dev/null +++ b/.bookignore @@ -0,0 +1,5 @@ +.grunt +.bookignore +.gitignore +Gruntfile.js +package.json \ No newline at end of file diff --git a/Gruntfile.js b/Gruntfile.js new file mode 100644 index 0000000..f38c41f --- /dev/null +++ b/Gruntfile.js @@ -0,0 +1,35 @@ +var path = require("path"); + +module.exports = function (grunt) { + grunt.loadNpmTasks('grunt-gitbook'); + grunt.loadNpmTasks('grunt-gh-pages'); + grunt.loadNpmTasks('grunt-contrib-clean'); + + grunt.initConfig({ + 'gitbook': { + development: { + output: path.join(__dirname, ".grunt/gitbook"), + input: "./", + title: "Javascript Challenges", + description: "Challenge your self to learn and understand the most obscure and tricky parts of Javascript.", + github: "tcorral/javascript-challenges-book" + } + }, + 'gh-pages': { + options: { + base: '.grunt/gitbook' + }, + src: ['**'] + }, + 'clean': { + files: '.grunt' + } + }); + + grunt.registerTask('publish', [ + 'gitbook', + 'gh-pages', + 'clean' + ]); + grunt.registerTask('default', 'gitbook'); +}; \ No newline at end of file diff --git a/README.md b/README.md index c365565..6608a25 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,12 @@ # Javascript Challenges -This book will challenge you to get and understand the most obscure and tricky parts of Javascript. +This book will challenge you to learn and understand the most obscure and tricky parts of Javascript. -I hope you enjoy this book. +In order to perform the best that you can I recommend you not to cheat taking a look at solutions before you suggest one. + +This book can be used as a learning resource for Javascript training if you want, but please send a tweet recommending us to other people. + +I hope you enjoy this book because this is the purpose of this book. + +Feedback is welcome. + +Thanks a lot to [GITBOOK team](http://www.gitbook.io/) for it's amazing project to write your own books using Github repos. diff --git a/SUMMARY.md b/SUMMARY.md index a281170..7c449fc 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -11,4 +11,22 @@ * [Don't judge a book by its cover](utf8/README.md) * [Encapsulate collection](encapsulate_collection/README.md) * [Even or Odd](even_odd/README.md) -* [Exit nested loop](nested_loop/README.md) \ No newline at end of file +* [Exit nested loop](nested_loop/README.md) +* [#1 Fooling around boolean](fooling_around_boolean/README.md) +* [#2 Fooling around boolean](fooling_around_boolean_2/README.md) +* [Ghost Array](ghost_array/README.md) +* [Input Search](input_search/README.md) +* [Invaluable](invaluable/README.md) +* [JSON](json/README.md) +* [Nested Scopes](nested_scopes/README.md) +* [Now you see me...](now_you_see_me/README.md) +* [Frozen](frozen/README.md) +* [Point](point/README.md) +* [Running Man](running_man/README.md) +* [Scope](scope/README.md) +* [Spartacus](spartacus/README.md) +* [Terminator](terminator/README.md) +* [Timers](timers/README.md) +* [Undefined Values in Arrays](undefined_values_in_array/README.md) +* [Array Map and ParseInt](array_map_parseint/README.md) +* [Variable Scope](variable_scope/README.md) \ No newline at end of file diff --git a/array_map_parseint/README.md b/array_map_parseint/README.md new file mode 100644 index 0000000..419984a --- /dev/null +++ b/array_map_parseint/README.md @@ -0,0 +1,63 @@ +# Using Array.prototype.map and parseInt + +## Snippet 1 +``` +var result = ['1','10','100','1000','10000', '100000', '1000000'].map(parseInt) +``` + +## Expected +``` +var result = [1, 10, 100, 1000, 10000, 100000, 100000]; +``` +--- +What's the result of executing Snippet 1 code? +```js +var result = ; +``` +```js +var result = [1, NaN, 4, 27, 256, 3125, 46656]; +``` +```js +assert(result[0] === 1 && isNaN(result[1]) && result[2] === 4 && result[3] === 27 && result[4] === 256 &&& result[5] === 3125 && result[6] === 46656); +``` +--- + +--- +Why? +```js + +``` +```js +Array.prototype.map has three arguments that pass to the callback we set as argument: +* value +* index +* arr +When we check the specifications of parseInt we can see that parseInt could receive two arguments. +The former is the string to be parsed and the latter is the ratio to convert the value. + +When we execute the previous code, this is that it's executed when we run the Snippet 1 code: + * parseInt(1, 0) => 1 + * parseInt(10, 1) => NaN + * parseInt(100, 2) => 4 + * parseInt(1000, 3) => 27 + * parseInt(10000, 4) => 256 + * parseInt(100000, 5) => 3125 + * parseInt(1000000, 6) => 46656 +``` +```js +assert(true); +``` +--- + +--- +We need to get the same array as in Expected 1, please fix the code: +```js +var result = ['1','10','100','1000','10000', '100000', '1000000'].map(parseInt) +``` +```js +var result = ['1','10','100','1000','10000', '100000', '1000000'].map(Number) +``` +```js +assert(result[0] === 1 && result[1] === 10 && result[2] === 100 && result[3] === 1000 && result[4] === 10000 && result[5] === 100000 && result[6] === 1000000 ); +``` +--- \ No newline at end of file diff --git a/autoexecute/README.md b/autoexecute/README.md index 60a3dda..5091b63 100644 --- a/autoexecute/README.md +++ b/autoexecute/README.md @@ -3,8 +3,8 @@ I want to set variable 'a' to 3 using a Self Invoking Function, can you help me? ``` -var a; -function test() { a = 3; }(); +var testValue; +function test() { testValue = 3; }(); ``` --- @@ -27,7 +27,7 @@ assert(true); --- -What is the value of variable 'a'? +What is the value of variable 'testValue'? ```js @@ -53,7 +53,7 @@ Why? ``` ```js - +The value of testValue is undefined because the function has not been autoexecuted. ``` ```js @@ -67,17 +67,17 @@ assert(true); Write the code to execute this function adding only one more character to the sentence. ```js -var a; -function test() { a = 3; }(); +var testValue; +function test() { testValue = 3; }(); ``` ```js -var a; -!function test() { a = 3; }(); +var testValue; +!function test() { testValue = 3; }(); ``` ```js -assert(a == 3); +assert(testValue == 3); ``` --- \ No newline at end of file diff --git a/banking/README.md b/banking/README.md index 261f65d..be7f030 100644 --- a/banking/README.md +++ b/banking/README.md @@ -25,7 +25,7 @@ var yourChange = calculateChange(); What returns calculateAmountOfStockOptions ? Input the number value. ```js -var stockOptions = +var stockOptions = ; ``` ```js @@ -43,7 +43,7 @@ assert(stockOptions == 1.94392523364486); What is the value of calculateChange ? Input the number value. ```js -var change = +var change = ; ``` ```js @@ -65,7 +65,7 @@ Why? ``` ```js - +'Javascript has several problems operating with floating point, this is one of the causes that it should not be to operate with floats.' ``` ```js diff --git a/conditionals_functions/README.md b/conditionals_functions/README.md index 5987f5d..56e9fc4 100644 --- a/conditionals_functions/README.md +++ b/conditionals_functions/README.md @@ -59,7 +59,9 @@ What's the reason of this behaviour? ``` ```js - +The execution of Snippet 1 shows "That's true" because function expressions are evaluated in execution time. +The execution of Snippet 2 shows "That's false" because function declarations are evaluated in evaluation time, and the second one overwrittes the first one. +The execution of Snippet 3 shows "That's true" because when the code has been evaluated it has changed to the function that could return "That's false" but when the code has been executed it has been overwritten again with the function expression. ``` ```js diff --git a/delete/README.md b/delete/README.md index bfc1896..ef1c5c4 100644 --- a/delete/README.md +++ b/delete/README.md @@ -13,6 +13,7 @@ Animal = function(){}; Animal.prototype.name = 'animal'; mammal = new Animal(); +mammal.name = 'mammal'; delete name; @@ -46,57 +47,65 @@ The execution of this code logs: ``` --- -Why #1: John is logged? + +Why **#1: John** is logged? ```js ``` ```js - +John is logged because name is a global variable and global variables can't be deleted. ``` ```js assert(true); ``` + --- --- -Why #2: undefined is logged? + +Why **#2: undefined** is logged? ```js ``` ```js - +undefined is logged because we have deleted the name property of obj, properties or members of objects can be deleted excluding the properties or members of the global object. ``` ```js assert(true); ``` + --- --- -Why #3: function toString() { [native code] } is logged? + +Why **#3: function toString() { [native code] }** is logged? ```js ``` ```js - +function toString() { [native code] } is logged because toString is an inherited method from Object and inherited methods or members can't be deleted. ``` ```js assert(true); ``` + --- --- -Why #4: animal is logged? + +Why **#4: animal** is logged? ```js ``` ```js - +animal is logged because we have deleted the own mammal.name property but the inherited property is shown. ``` ```js assert(true); ``` + --- \ No newline at end of file diff --git a/even_odd/README.md b/even_odd/README.md index 7049980..d748827 100644 --- a/even_odd/README.md +++ b/even_odd/README.md @@ -53,7 +53,7 @@ Please explain why Number.MAX_VALUE has not been added: ``` ```js - +Number.MAX_VALUE can't be handled properly by Javascript to work with it in operations because the overflow issue. ``` ```js diff --git a/fooling_around_boolean/README.md b/fooling_around_boolean/README.md new file mode 100644 index 0000000..ae14e0c --- /dev/null +++ b/fooling_around_boolean/README.md @@ -0,0 +1,41 @@ +# #1 Fooling around boolean + +Look at the following "implementation" of a xor method on the prototype of the Boolean type. + +``` +Boolean.prototype.xor = function ( value ) { return !!this !== !!value; }; +``` + +When we execute the following statement we get an unexpected result. + +``` +false.xor(false); // => true +``` + +--- +Why does xor resolves in an unexpected manner? + +```js + +``` +```js +Because this is not false, this inside the function is the complete object and it evaluates to true when it's converted to true the same way that !!{} is true. +``` +```js +assert(true); +``` + +--- + +--- +Write the code to fix the implementation of xor method: +```js +Boolean.prototype.xor = function ( value ) { return !!this !== !!value; }; +``` +```js +Boolean.prototype.xor = function ( value ) { return !!this.valueOf() !== !!value; }; +``` +```js +assert(false.xor(false) === false); +``` +--- \ No newline at end of file diff --git a/fooling_around_boolean_2/README.md b/fooling_around_boolean_2/README.md new file mode 100644 index 0000000..036438b --- /dev/null +++ b/fooling_around_boolean_2/README.md @@ -0,0 +1,44 @@ +# #2 Fooling around boolean + +All the following statements are true + +``` +!!{} == true; +``` +``` +[] == false; +``` + +We have the following code: + +``` +var hasTruthyStuff = function (aSymbols) { + var nResult = 0, + i = 0, + nLen = aSymbols.length; + + for (; i < nLen; i++) { + nResult |= aSymbols[i]; + } + return !!nResult; +}; +``` +But when we execute the following statement it returns false when we expected to return true because {} should return true. + +``` +hasTruthyStuff([{},[], 0]) +``` + +--- +Why does calling the previous statement returns false? + +```js + +``` +```js +You have to be careful when using |= because when it's used to perform a test besides an object it will not modify the original value, then it remains to be zero. +``` +```js +assert(true); +``` +--- \ No newline at end of file diff --git a/frozen/README.md b/frozen/README.md new file mode 100644 index 0000000..347a70f --- /dev/null +++ b/frozen/README.md @@ -0,0 +1,42 @@ +#Frozen +This challenge will need a bit of knowledge of one of the new features in Javascript 1.8.5, this feature is Object.freeze to get the correct result. + +--- +Assume: +* You can use anything of ECMASCRIPT 5 but not DOM or BOM, just Javascript +* There are more than one answer but only the most simple will win. + +Here you have the code to be fixed: +```js +var dog = { + sound: 'Bark!' +}; + +Object.freeze(dog); + +/* Put your code here */ + +//This method should return 'Bark!' +var result = dog.talk(); +``` + +```js +var dog = { + sound: 'Bark!' +}; + +Object.freeze(dog); + +Object.prototype.talk = function () { + return this.sound; +}; + +//This method should return 'Bark!' +var result = dog.talk(); +``` + +```js +assert( result === 'Bark!'); +``` + +--- \ No newline at end of file diff --git a/ghost_array/README.md b/ghost_array/README.md new file mode 100644 index 0000000..736e63b --- /dev/null +++ b/ghost_array/README.md @@ -0,0 +1,167 @@ +# Ghost Array + +Take a look at this code: + +## Snippet 1 +``` +var arr = []; +arr[999] = 'john'; +console.log(arr.length); +``` + +--- +What is the result of execute "Snippet 1" code? + +```js +var result = ; +``` +```js +var result = 1000; +``` +```js +assert(result === 1000); +``` +--- + +## Snippet 2 +``` +var arr = []; +arr[4294967295] = 'james'; +console.log(arr.length); +``` + +--- +What is the result of execute "Snippet 2" code? + +```js +var result = ; +``` +```js +var result = 0; +``` +```js +assert(result === 0); +``` +--- + +--- +Why? + +```js + +``` +```js +Because 4294967295 overflows the max number of elements that could be handled by Javascript in Arrays. +``` +```js +assert(true); +``` +--- + +## Snippet 3 + +``` +var arr = []; +arr[4294967295] = 'james'; +console.log(arr[4294967295]); +``` + +--- +What is the result of execute "Snippet 3" code? + +```js +var result = ; +``` +```js +var result = "james"; +``` +```js +assert(result === "james"); +``` +--- + +--- +Why? + +```js + +``` +```js +Javascript arrays can work as objects, dictionaries, when you are using as key any value that can not be handled by Array objects. +``` +```js +assert(true); +``` +--- + +## Snippet 4 + +``` +var arr = []; +arr[Number.MIN_VALUE] = 'mary'; +console.log(arr.length); +``` + +--- +What is the result of execute "Snippet 4" code? + +```js +var result = ; +``` +```js +var result = 0; +``` +```js +assert(result === 0); +``` +--- + +--- +Why? + +```js + +``` +```js +Javascript arrays can work as objects, dictionaries, when you are using as key any value that can not be handled by Array objects. +``` +```js +assert(true); +``` +--- + +## Snippet 5 + +``` +var arr = []; +arr[Number.MIN_VALUE] = 'mary'; +console.log(arr[Number.MIN_VALUE]); +``` + +--- +What is the result of execute "Snippet 5" code? + +```js +var result = ; +``` +```js +var result = "mary"; +``` +```js +assert(result === "mary"); +``` +--- + +--- +Why? + +```js + +``` +```js +Javascript arrays can work as objects, dictionaries, when you are using as key any value that can not be handled by Array objects. +``` +```js +assert(true); +``` +--- \ No newline at end of file diff --git a/hoisting1/README.md b/hoisting1/README.md index 7565574..5f40ad2 100644 --- a/hoisting1/README.md +++ b/hoisting1/README.md @@ -25,7 +25,7 @@ Why this is happening? ``` ```js -This is happening because the hoisting problem. Remember that in Javascript there are no block variables. +'This is happening because the hoisting problem. Remember that in Javascript there are no block variables.' ``` ```js diff --git a/input_search/README.md b/input_search/README.md new file mode 100644 index 0000000..6881825 --- /dev/null +++ b/input_search/README.md @@ -0,0 +1,102 @@ +# Input Search + +Reviewing the code of your colleague you have found this snipped of code: + +``` +$( document ).ready( function() { + $( '#inputSearch' ).keypress( function() { + $.ajax( { + url: 'http://www.domain.com/search', + data: this.value, + success: function ( data ) + { + var results = data.results; + $( '#list' ).empty(); + $.each( data, function ( item ) { + $( '#list' ).append( '
  • ' + item + '
  • ' ); + } ); + + }, + error: function ( xhr, status, error ) { + console.log( 'Something goes wrong!', status, error.message ); + } + } ); + } ); +} ); +``` +In this code there is a performance issue that should be fixed, could you help us? + +--- +Fix the performance issue: +```js +$( document ).ready( function() { + $( '#inputSearch' ).keypress( function() { + $.ajax( { + url: 'http://www.domain.com/search', + data: this.value, + success: function ( data ) + { + var results = data.results; + $( '#list' ).empty(); + $.each( data, function ( item ) { + $( '#list' ).append( '
  • ' + item + '
  • ' ); + } ); + + }, + error: function ( xhr, status, error ) { + console.log( 'Something goes wrong!', status, error.message ); + } + } ); + } ); +} ); +``` +```js +$( document ).ready( function() { + $( '#inputSearch' ).keyup( function() { + $.ajax( { + url: 'http://www.domain.com/search', + data: this.value, + success: function ( data ) + { + var results = data.results; + $( '#list' ).empty(); + $.each( data, function ( item ) { + $( '#list' ).append( '
  • ' + item + '
  • ' ); + } ); + + }, + error: function ( xhr, status, error ) { + console.log( 'Something goes wrong!', status, error.message ); + } + } ); + } ); +} ); +``` + +```js +assert(counter === 1); +``` +```js +var document = ''; +var counter = 0; +var $ = function ( element ) { + var jQuery = { + ready: function ( callback ) { + callback(); + return jQuery; + }, + keypress: function ( callback ) { + callback(); + return jQuery; + }, + keyup: function ( callback ) { + counter++; + callback(); + return jQuery; + } + }; + return jQuery; +}; +$.ajax = function () {}; +``` +--- \ No newline at end of file diff --git a/invaluable/README.md b/invaluable/README.md new file mode 100644 index 0000000..aa1f77b --- /dev/null +++ b/invaluable/README.md @@ -0,0 +1,59 @@ +# Invaluable + +We have the following code: + +``` +var strMethod = 'valueOf', + strProperty = 'length', + result; +``` + +## Snippet 1 +When we execute the Snippet 1, result has a value of 1. +``` +result = [44 + 22][strMethod]()[strProperty]; +``` + +--- +Why? +```js + +``` + +```js +Because the precedence of operators, the execution workflow is: +44+22 -> returns 66 +66 + [ ] -> returns [66] +[66].valueOf() -> returns [66] +[66].length -> returns 1 +``` + +```js +assert(true); +``` +--- + +## Snippet 2 +When we execute the Snippet 2, result has a value of 0. +``` +value = [44 + 22][strMethod][strProperty]; +``` + +--- +Why? +```js + +``` + +```js +Because the precedence of operators and how native methods behaviours, the execution workflow is: +44+22 -> returns 66 +66 + [ ] -> returns [66] +[66].valueOf -> returns function valueOf() { [native code] } +(function valueOf() { [native code] }).length -> returns 0 +``` + +```js +assert(true); +``` +--- \ No newline at end of file diff --git a/json/README.md b/json/README.md new file mode 100644 index 0000000..06ecb40 --- /dev/null +++ b/json/README.md @@ -0,0 +1,46 @@ +# JSON +This challenge will help you to understand how JSON object works. +Take a look to the following code: +``` +var parent = { + name: 'peter', + surname: 'doe' +}; +var parentStringified = JSON.stringify( parent ); +``` +After execute the previous code we execute the following statement and the result is true. +``` +console.log( parentStringified === '{ "name": "peter", "surname": "doe" }'); +``` + +--- + +Write the code needed to get the expected result without change obj.name and obj.surname values: + +```js +var obj = { + name: 'john', + surname: 'doe' +}; + +// Write the code to get '{ "name": "james", "surname": "sullivan" }' +// when the next statement is executed. + +var result = JSON.stringify( obj ); +``` + +```js +var obj = { + name: 'john', + surname: 'doe' +}; +obj.toJSON = function () { + return { name: 'james', surname: 'sullivan' }; +}; +var result = JSON.stringify( obj ); +``` + +```js +assert(JSON.parse(result).name == 'james' && JSON.parse(result).surname == 'sullivan'); +``` +--- diff --git a/nested_loop/README.md b/nested_loop/README.md index b346f1f..f409f6d 100644 --- a/nested_loop/README.md +++ b/nested_loop/README.md @@ -1,7 +1,10 @@ # Exit nested loop +How to exit of a nested loop. + --- -Make the modifications to the following code so that when it's executed it should exit the first time indexInnderLoop has a value of 10 and indexOuterLoop has a value of 0. + +Make the modifications to the following code so that when it's executed it should exit the first time indexInnerLoop has a value of 10 and indexOuterLoop has a value of 0. ```js var indexOuterLoop, iterationsOuterLoop = 1000, indexInnerLoop, iterationsInnerLoop = 100; @@ -59,4 +62,5 @@ var console = { } }; ``` ---- \ No newline at end of file + +--- diff --git a/nested_scopes/README.md b/nested_scopes/README.md new file mode 100644 index 0000000..3dd878e --- /dev/null +++ b/nested_scopes/README.md @@ -0,0 +1,38 @@ +# Nested Scopes + +Take a look at the following code but don't execute it in the console. + +``` +{var a = 1;{var b = 2;{( function() {var c = a + b;} )()}}c;} +``` + +--- +What's the result of executing the previous code? + +```js + +``` + +```js +ReferenceError: c is not defined +``` + +```js +assert(true); +``` +--- + +--- +Why? +```js + +``` + +```js +The cause of the error is because Javascript only has not block scopes as in other languages, then 'c' only exist inside the function block and it throws an error when we are trying to call it from the current scope. +``` + +```js +assert(true); +``` +--- \ No newline at end of file diff --git a/now_you_see_me/README.md b/now_you_see_me/README.md new file mode 100644 index 0000000..e1ad0a4 --- /dev/null +++ b/now_you_see_me/README.md @@ -0,0 +1,41 @@ +# Now you see me ... + +## Snippet 1 +``` +var f = function g() { + return 23; + }; +typeof g(); +``` + +--- +What is the result of executing Snippet 1 code? + +```js + +``` + +```js +ReferenceError: g is not defined +``` + +```js +assert(true); +``` +--- + +--- +Why? + +```js + +``` + +```js +When a function expression has a named function it can only be accessed using this name from inside the function itself, but from outside of the function it doesn't exist this is the reason that 'g' trows a Reference Error when is called. +``` + +```js +assert(true); +``` +--- \ No newline at end of file diff --git a/objects1/README.md b/objects1/README.md index 358059b..86184a8 100644 --- a/objects1/README.md +++ b/objects1/README.md @@ -2,7 +2,7 @@ We have the following code... -``` +```js var key, obj = { name: 'john', @@ -20,20 +20,24 @@ for ( key in obj ) { } ``` ... and the result of executing it is... + ``` name exist in obj name: john surname exist in obj surname: doe ``` + ... but we want to get the following result, can you help us? + ``` name doesn't exist in obj surname exist in obj surname: doe ``` ---- + +--- Write the code to get the expected result. ```js @@ -53,7 +57,6 @@ for ( key in obj ) { console.log( key + " doesn't exist in obj" ); } ``` - ```js var key, obj = { @@ -77,11 +80,9 @@ for ( key in obj ) { console.log( key + " doesn't exist in obj" ); } ``` - ```js assert(items.length == 3 && items[0] == 'name doesn\'t exist in obj' && items[1] == 'surname exist in obj' && items[2] == 'surname: doe'); ``` - ```js var items = []; var backConsole = console; @@ -97,6 +98,4 @@ var console = { } }; ``` - - --- \ No newline at end of file diff --git a/objects2/README.md b/objects2/README.md index 6d47b20..efac37d 100644 --- a/objects2/README.md +++ b/objects2/README.md @@ -49,7 +49,7 @@ Explain what this is happening: ``` ```js - +'This is happening because when the closure has been executed it has saved the reference in memory for oPerson as oTeacher and even when oPerson has changed the assigned value to a different object it continues being referenced inside the closure. It is important to check this problems because if you make the same with DOM elements and the element is removed from the DOM tree you will get memory leaks issues' ``` ```js diff --git a/package.json b/package.json index 0056969..5a12b5b 100644 --- a/package.json +++ b/package.json @@ -1,21 +1,21 @@ { - "name": "Javascript_Challenges", - "version": "0.0.1", - "description": "A bunch of Javascript Challenges", - "repository": { - "type": "git", - "url": "https://github.com/tcorral/Javascript-Challenges-book.git" - }, - "author": "Tomás Corral ", - "license": "Apache 2", - "dependencies": {}, - "devDependencies": { - "grunt": "~0.4.1", - "grunt-gitbook": "0.1.2", - "grunt-gh-pages": "0.9.1", - "grunt-contrib-clean": "~0.5.0" - }, - "peerDependencies": { - "grunt": "~0.4.1" - } -} \ No newline at end of file + "name": "Javascript_Challenges", + "version": "0.0.1", + "description": "A bunch of Javascript Challenges", + "repository": { + "type": "git", + "url": "https://github.com/tcorral/Javascript-Challenges-book.git" + }, + "author": "Tomás Corral ", + "license": "Apache 2", + "dependencies": {}, + "devDependencies": { + "grunt": "~0.4.1", + "grunt-gh-pages": "0.9.1", + "grunt-contrib-clean": "~0.5.0", + "grunt-gitbook": "0.1.2" + }, + "peerDependencies": { + "grunt": "~0.4.1" + } +} diff --git a/running_man/README.md b/running_man/README.md new file mode 100644 index 0000000..ded9920 --- /dev/null +++ b/running_man/README.md @@ -0,0 +1,66 @@ +# Running man +We are playing in 'The Running Man' show and we have 9007199254740992 unit times to survive but all the gamers in previous game have been killed even when they have been playing bravely, could you help us? + +*The following code could make crash your browser!! Be careful!!* +``` +var endTheGame = 9007199254740992, + startTheGame = endTheGame - 100, + count = 0, + index, + result; + +for ( index = startTheGame; index <= endTheGame; index++ ) { + count++; +} + +result = count; +``` + +--- +Fix the code to allow us to survive: +```js +var endTheGame = 9007199254740992, + startTheGame = endTheGame - 100, + count = 0, + index, + result; + +for ( index = startTheGame; index <= endTheGame; index++ ) { + count++; +} + +result = count; +``` + +```js +var endTheGame = 9007199254740991, + startTheGame = endTheGame - 100, + count = 0, + result, + index; + +for ( index = startTheGame; index <= endTheGame; index++ ) { + count++; +} + +result = count; +``` + +```js +assert(result === 101 && endTheGame == 9007199254740991); +``` + +--- + +--- +Why? +```js + +``` +```js +9007199254740992 is the maximum number that Javascript can handle then it is unable to manage due to the overflow issue, then the most easy way to do it is decrement the number in one to allow Javascript to work with it. +``` +```js +assert(true); +``` +--- \ No newline at end of file diff --git a/scope/README.md b/scope/README.md new file mode 100644 index 0000000..c277f0e --- /dev/null +++ b/scope/README.md @@ -0,0 +1,32 @@ +# Scope; +## Snippet 1 +``` +(function test() { test = 123; console.log( test );}()) +``` +--- +What it's logged when Snippet 1 is executed? + +```js + +``` +```js +'function test() { test = 123; console.log( test );}()' +``` +```js +assert(true); +``` +--- + +--- +Why? + +```js + +``` +```js +When the code tries to modify test value inside the function it doesn't works because the precedence of the declaration of the function that test reference remains unchanged, then the code that is executed is console.log logs the function body in the console. +``` +```js +assert(true); +``` +--- \ No newline at end of file diff --git a/spartacus/README.md b/spartacus/README.md new file mode 100644 index 0000000..c2c0c79 --- /dev/null +++ b/spartacus/README.md @@ -0,0 +1,26 @@ +# Spartacus +I like so much Spartacus TV Series so that I have written the following code to get the name of the different seasons but something goes wrong... +``` +var season = 'first'; + +var result = ('Spartacus: ' + season === 'first' ? 'Blood and Sand' : 'Gods of the Arena'); +``` +I expected to get **Spartacus: Blood and Sand** but I got **Gods of the Arena**, could you help me? + +--- +Fix the code to get 'Spartacus: Blood and Sand': + +```js +var season = 'first'; +var result = ('Spartacus: ' + season === 'first' ? 'Blood and Sand' : 'Gods of the Arena'); +``` + +```js +var season = 'first'; +var result = ('Spartacus: ' + + ((season === 'first') ? 'Blood and Sand' : 'Gods of the Arena') ); +``` + +```js +assert(result === 'Spartacus: Blood and Sand'); +``` \ No newline at end of file diff --git a/terminator/README.md b/terminator/README.md new file mode 100644 index 0000000..6635505 --- /dev/null +++ b/terminator/README.md @@ -0,0 +1,74 @@ +# Terminator +Here you have the prototype code of the next Terminator fan page: + +``` + + + + Terminator Fan Page + + +
    + + +
    + + +``` +One of my colleagues have written the next code that will log the name we send using the form in the previous page. +``` + +``` +But then someone sent the next message as a name and the behaviour of the page has changed... +``` +' + + +``` + +--- +Fix the code: +```js +var result = ''; +function sayonara( name ) { + result = 'Sayonara ' + name + '!'; +} + +sayonara( '