Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

General JavaScript

Featured Replies

Thank you for advice with course! I passed this course. I used webpack with localhost for this app. It working. But for next step i need to save text, because when i close browser, text dessapeared. Can you give me advice - what technologies is the best for my needs? LocalStorage, MongoDB? Or maybe it outdated now and there are new trends in this area?

 

PS. fetch is working. I understand that i have problem with paths in webpack, because i see in console that file.json is underfined.

  • Replies 422
  • Views 68.4k
  • Created
  • Last Reply

Top Posters In This Topic

Most Popular Posts

  • As soon as I saw the JS videos with that Mattias guy, I knew who he was straight away. He posts some really useful answers on Quora. I'd advise signing up if you haven't already. I've wasted hours re

  • Console.table, ladies and gentleman http://jsfiddle.net/juu5fx82/.   You need to use the JS console obviously, and hit 'run'. I never knew this existed.

  • jQuery's modular, you can build a custom version via Grunt, its pretty simple.   Before v3.0, which now uses requestAnimationFrame and Promises/A+, I'd use a build without Effects and Ajax with Velo

  • Author

Thank you for advice with course! I passed this course. I used webpack with localhost for this app. It working. But for next step i need to save text, because when i close browser, text dessapeared. Can you give me advice - what technologies is the best for my needs? LocalStorage, MongoDB? Or maybe it outdated now and there are new trends in this area?

 

PS. fetch is working. I understand that i have problem with paths in webpack, because i see in console that file.json is underfined.

 

It depends on whether you just want the data to be available again when a user revisits a site, or if you want to render the app to be usable completely offline. LocalStorage will work in both cases, but it does have a storage limit that varies across browsers.

 

I'd recommend looking at the Service Worker API if you want a completely offline experience, otherwise, if you're just storing things like form values, then LocalStorage is perfectly fine.

 

In both cases, it shouldn't be something your app completely relies upon because browser support isn't there for all features. Service Workers especially should be treated as more of an enhancement.

Thank you very much, Jack! I will take a look on both :)

Edited by fleur

Today i was asked to pass the test.

function bind(method, context) { 
   var args = Array.prototype.slice.call(arguments, 2); 
   return function() { 
       var a = args.concat(Array.prototype.slice.call(arguments, 0)); 
       return method.apply(context, a); 
    }
}

The question was: how this function working and for what it can be used.

I understand that function bind (and return function too) convert array-like arguments into a real array. Method and context is not converted into array (because of 2 index). I can pass extra args in bind function and args into returned function and call method with context as 'this'.

My question is - how it can be used, in what cases. Is method and context - function or objects, or function and object? If someone can provide live example it will be awesome!

Edited by fleur

Today i was asked to pass the test.

function bind(method, context) { 
   var args = Array.prototype.slice.call(arguments, 2); 
   return function() { 
       var a = args.concat(Array.prototype.slice.call(arguments, 0)); 
       return method.apply(context, a); 
    }
}

The question was: how this function working and for what it can be used.

I understand that function bind (and return function too) convert array-like arguments into a real array. Method and context is not converted into array (because of 2 index). I can pass extra args in bind function and args into returned function and call method with context as 'this'.

My question is - how it can be used, in what cases. Is method and context - function or objects, or function and object? If someone can provide live example it will be awesome!

 

This looks to be the same as the .bind() function that returns a new function with hard bound 'this' context although it seems pointless as JavaScript already provides such a function on the function prototype.

Robert, thank you very much! I was confused with arguments also.

I saw Mattias video's not a one time and decided make something similar. Because in front end the most common task is to get values from nested objects, i tried to use recursion and reduce for that. For example if i have nested object

 

let someList = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

How i can get values in reverse order? I tried this

 

function reversePrint(node) {


Object.keys(node).map(key => {
let myKey = node[key];
if(typeof myKey == "object") {
   reversePrint(myKey);
  } 
   console.log(myKey);      
});

}
reversePrint(someList);

Worked, but not in reverse order and i have mistake with null.

 

 

Also i tried push values to an array, but i don't understand why every value create it's own array?

 

function reversePrint(node) {


Object.keys(node).reduce((array, key) => {
let myKey = node[key];
if(typeof myKey == "object") {
 reversePrint(myKey);
 } 
 array.push(myKey);
 console.log(array);
}, []);


}
reversePrint(someList);

I will be very greatfull for advice where to find a mistake.


const someList = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null
}
}
}
};

const recurse = ({ value, next }, acc) => {
acc.push(value);
if (next) {
return recurse(next, acc);
}
return acc;
};

const newList = recurse(someList, []);
console.log(newList.reverse()); // [4, 3, 2, 1]

 

Edited by rbrtsmith

Awesome! Thank you very much! If understand right - there is in destruction { value, next }

value - 1

next  - {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null
}
}
}

And if (next) means (if 'object)?

 

Can i ask - what mistake was in my function? What if i will have a task to can get values from random names, not only from value and next.

yes I am using destructuring for the argument. An if statement will check the truthiness of an expression. An object is a truthy value. null, which you have used where there is no object assigned is falsy. You don't have to test for an object in your example, just test if the value is truthy or not. Keeps things more concise :)

Thank you !!! I understand the things that i didn't understand in the past for a long time :)

I just watching Dan Abramov lessons and see the unknown syntax

[action.id]: todo(state[action.id], action)

It means that all ids will combine in array. Can someone tell me, please, how this syntax is called?

 

[action.id]:

 

Looks like some sort of object name destruction. I want to seach more about it but i need to know how it called at first.

Edited by fleur

It's a computed property.

By using square brackets we're no longer limited to using strings as object keys, we can use variables and expressions etc.

Wynn, thank you much! I will search for more practical examples for to see this in action.

I don't think there's much else to it, the same way you can have computed values to reference an object like when chaining:
foo.bar[bam].someOtherProp()

 

A practical example is when you are building up an object with computed keys, like incrementing them or something.

I still think you should spend more time building React Apps though before you delve too much into Redux as you can see from this very handy guide to learning React, it comes in pretty late https://github.com/petehunt/react-howto. (Assuming the Dan Abramhov course is a Redux one...)

Edited by rbrtsmith

Thank you very much for advice and link! I can't continue learning Dan Abramov course about Router because he use Node.js and Express.js for dev server. I don't know it :) So.. yes, i agree, it's better for me to make something on React first. I am going to make deleteTodo and editTodo function for practise.

Edited by fleur

  • Author

https://hyperterm.org/

 

This is a pretty interesting project, it's basically designed to be a hackable terminal built with JS, just like Atom is for code editing. A plugin based terminal that uses NPM has a lot of potential IMO.

JS experts...

 

I'll be spending a lot of time on an aeroplane soon so am looking at getting some books to read. I've already got the first 'You Don't Know JS' book and am looking at:

 

You Don't Know JS: Scope & Closures

You Don't Know JS: This & Object Prototypes

 

Both of these books were released in 2014 though so are they out of date or still gold?

 

Thanks in advance :)

They're gold. He's teaching low level fundamentals - things that are unlikely to change for a long time. I would advise you check out his other books too: ES6 and Async.

  • Author

Just looking at ES6 makes me want to vomit to be honest. I'll do the others first. I'd like to think my JS is improving over time so once I have that nailed down a bit more I'll start looking at the crazy syntax of ES6 (I know there's more to it than that but can't bring myself to look into it any more than that at present).

 

Most of the ES6 syntax I've come across isn't too bad, but arrow functions can take a while to get used to if you've been writing function() for years, especially when people remove the parentheses and nest functions. At the very least they could have kept the parentheses in the same place as function(), it seems like an unusual design, but I'm sure there's a reason for it.

 

Personally, I like to keep the parens even when they can be omitted, I find it easier to scan because it resembles a function still, and it keeps all of your arrow functions looking consistent.

 

x =>
(x) =>

 

 

Most of the ES6 syntax I've come across isn't too bad, but arrow functions can take a while to get used to if you've been writing function() for years, especially when people remove the parentheses and nest functions. At the very least they could have kept the parentheses in the same place as function(), it seems like an unusual design, but I'm sure there's a reason for it.

 

Personally, I like to keep the parens even when they can be omitted, I find it easier to scan because it resembles a function still, and it keeps all of your arrow functions looking consistent.

 

x =>
(x) =>

 

I used to think the same, but now after using arrow functions for a long time it doesn't make any difference if there are brackets around the single variable, the arrow itself denotes that it is a function call. Similarly I found concise function calls on object methods confusing to read at first, but soon enough it starts to become a familiar pattern.

 

@@NOCK don't try to learn ES6 all in one go, just learn it bit by bit. This is how I also learnt Sass, as like Sass ES5 is perfectly valid in ES6 so you just can use the bits you know and overtime introduce new features. Start with let and const and once they are comfortable add in arrows or object destructuring and so on.

Edited by rbrtsmith

  • 2 months later...
  • Author

This is very high-level at times but just push through if you're interested in where React is (possibly) heading. Some of it went way over my head, but the integrated layout stuff (28:50) sounds amazing.

 

 

Webpack takes a bit of time to wrap your head around but it's really powerful, however if you are not interested in things like bundling images and styles with your JavaScript, code splitting and tree shaking then you are better off with other tools. If you only want to bundle JS then Browserify is a more lightweight tool.

This is very high-level at times but just push through if you're interested in where React is (possibly) heading. Some of it went way over my head, but the integrated layout stuff (28:50) sounds amazing.

 

Pretty mindblowing! I shall be investigating Fibre in the coming months!

  • 3 months later...

I've always struggled to grasp recursion, I'm not sure why. I think it's just difficult to visualise what is going on so I decided to spend a bit of time improving my understanding of recursive algorithms.

 

I've created this repo because I thought it might be useful to others who are looking to improve their understanding of recursion in JavaScript, and also for those looking to improve their unit testing skills. All the recursive functions here were written in the TDD fashion using Jest. https://github.com/rbrtsmith/javascript-recursive-functions

  • Author

I've always struggled to grasp recursion, I'm not sure why. I think it's just difficult to visualise what is going on so I decided to spend a bit of time improving my understanding of recursive algorithms.

 

I've created this repo because I thought it might be useful to others who are looking to improve their understanding of recursion in JavaScript, and also for those looking to improve their unit testing skills. All the recursive functions here were written in the TDD fashion using Jest. https://github.com/rbrtsmith/javascript-recursive-functions

 

Looking at something like the reverse array tests, is there a reason you don't use describe functions? The same tests could be written as:

describe('array reverse', () => {
  it('should take a valid array as an argument', () => {
    expect(reverseArray('hello')).toEqual('You must pass in an array');
  });

  it('should display a sequence of items in reverse order', () => {
    expect(reverseArray(['a', 'b', 'c', 'd'])).toEqual(['d', 'c', 'b', 'a']);
  });
});

I'm not that experienced in this area so I'm guessing It's intentional, but wouldn't the array reverse test pass without showing what it's passing on, or what tests are included as part of it? I'm trying to get better at TDD so I'm always curious to see what other people are doing.

 

Looking at something like the reverse array tests, is there a reason you don't use describe functions? The same tests could be written as:

describe('array reverse', () => {
  it('should take a valid array as an argument', () => {
    expect(reverseArray('hello')).toEqual('You must pass in an array');
  });

  it('should display a sequence of items in reverse order', () => {
    expect(reverseArray(['a', 'b', 'c', 'd'])).toEqual(['d', 'c', 'b', 'a']);
  });
});

I'm not that experienced in this area so I'm guessing It's intentional, but wouldn't the array reverse test pass without showing what it's passing on, or what tests are included as part of it? I'm trying to get better at TDD so I'm always curious to see what other people are doing.

 

'describe', 'it' and 'test' are all globals provided by Jest. These globals differ depending on the test runner you use. Mocha has 'describe' and 'it'. Tape has 'test'.

How you structure them is upto you. It all depends on how you want your test results to be logged to the console. With jest, the important part is the 'expect' function.

 

I just chose to do it this way because it's a little less verbose and less typing. If I am say testing React component that could look something like this

 

 

describe('<User />', () => {
  it('displays the users name', () => {
     // insert assertion
  });
  it('displays the users id', () => {
     // insert assertion
  });
  it('displays the users email', () => {
     // insert assertion
  });
});

Whereas the reverseArray function was only really doing one thing, as opposed to the User component above that has 3 parts to be tested.

 

This is how passing tests come out:

 [282] → yarn unit
yarn unit v0.17.10
$ jest
 PASS  functions/mergeSort/__tests__/index.js
 PASS  functions/filter/__tests__/index.js
 PASS  functions/fibonacci/__tests__/index.js
 PASS  functions/map/__tests__/index.js
 PASS  functions/factorial/__tests__/index.js
 PASS  functions/reverseArray/__tests__/index.js
 PASS  functions/fizzbuzz/__tests__/index.js
 PASS  functions/reverseString/__tests__/index.js

Test Suites: 8 passed, 8 total
Tests:       10 passed, 10 total
Snapshots:   0 total
Time:        2.049s
Ran all test suites.
✨  Done in 3.72s.

If I make the reverseArray fail by putting a false value in the expected block this is output

 

yarn unit v0.17.10
$ jest
 PASS  functions/mergeSort/__tests__/index.js
 PASS  functions/factorial/__tests__/index.js
 PASS  functions/fizzbuzz/__tests__/index.js
 PASS  functions/map/__tests__/index.js
 PASS  functions/filter/__tests__/index.js
 FAIL  functions/reverseArray/__tests__/index.js
  ● reverseArray

    expect(received).toEqual(expected)

    Expected value to equal:
      ["d", "c", "b", "d"]
    Received:
      ["d", "c", "b", "a"]

    Difference:

    - Expected
    + Received

    @@ -1,6 +1,6 @@
     Array [
       "d",
       "c",
       "b",
    -  "d",
    +  "a",
     ]

      at Object.<anonymous> (functions/reverseArray/__tests__/index.js:4:76)
      at process._tickCallback (internal/process/next_tick.js:103:7)

 PASS  functions/fibonacci/__tests__/index.js
 PASS  functions/reverseString/__tests__/index.js

Test Suites: 1 failed, 7 passed, 8 total
Tests:       1 failed, 9 passed, 10 total
Snapshots:   0 total
Time:        2.197s
Ran all test suites.
error Command failed with exit code 1.

This feels like plenty of information to me. But of course for functions that are doing multiple things (typically I think functions should do as few things as possible, preferably one) like a React component a describe block will make the output more readable.

 

I think @@citypaul could expand on this seen as he is the man to talk to when it comes to testing :)

Edited by rbrtsmith

Jest comes with coverage built in so you don't need to mess around setting up something like Istanbul, it also ships with an assertion library. It has dead easy to mock functions, so there's no need for a mocking library. Essentially it's just fully featured and we use it in work so I'm becoming more familiar with it's API.

As far as I know you can still import your own assertions, but I almost always use Equal / deepEqual or an equivalent. I'm aware there's a bunch of others but I feel like my tests read better when I write them consistently like this.

  • Author

As far as I know you can still import your own assertions, but I almost always use Equal / deepEqual or an equivalent. I'm aware there's a bunch of others but I feel like my tests read better when I write them consistently like this.

 

Do you test your React components at work? I'm a bit torn with UI tests, I completely understand testing your API, modules etc, but UI seems so fragile and subject to a lot of change that I'm not sure if there's value. Brain talks about this in the FEM React course, he doesn't really do component testing, but shows you how to do it anyway with Jest.

 

I've only done one project test-first which was a stamp duty calculator, I knew it would be a good starting project to use TDD with and it worked out really well. I could see the advantages right away and I've had to go back since and add additional calculations, which I've been able to do without breaking the API and having to test every single moving part again.

 

I used Mocha and Chai on this, but I'd like to get a little more familiar with writing tests for PHP so that we can have frontend and backend coverage, but frameworks like PHP Unit just aren't as nice as ones in the JS community, so I'll probably just stick to front end for now and concentrate on getting more disciplined at writing tests for that.

 

Do you test your React components at work? I'm a bit torn with UI tests, I completely understand testing your API, modules etc, but UI seems so fragile and subject to a lot of change that I'm not sure if there's value. Brain talks about this in the FEM React course, he doesn't really do component testing, but shows you how to do it anyway with Jest.

We were testing them using Enzyme, which is a nicer API that wraps ReactTestUtils but we were only testing minimally. For example if we have a component that maps over some data and renders a list of child components as a result, we would test that logic only. So we would write some mock data, pass it to the component and check that the right number of child components get rendered.

 

Now thought due to the issues you outlined Jest has added snapshot testing which we've experimented with but it's early days with that. So we're focusing mostly on writing tests that are actually beneficial rather than trying to get 100% coverage. i.e. quite a few of our presentational components remain untested.

 

I'd encourage you to try out Jest, it has very minimal setup. It just pretty much works outside of the box. It doesn't ship with Enzyme however as that is something AirBnb have open sourced.

Edited by rbrtsmith

Jest comes with coverage built in so you don't need to mess around setting up something like Istanbul, it also ships with an assertion library. It has dead easy to mock functions, so there's no need for a mocking library. Essentially it's just fully featured and we use it in work so I'm becoming more familiar with it's API.

 

Have you used tape and if so, which would you say is better, Tape vs Jest?

 

I'm currently getting to grips with Mocha and Chai but I've seen Eric Elliott mention that we should be using Tape instead, but no mention of Jest. I've looked at a few Jest examples and it looks good.

 

To be honest, in a lot of these cases it tends to be that people like to use the tools they're used to. Some of the tools may have advantages over others, but I've personally seen little reason to move from Mocha/Chai and Jasmine for most JS stuff in general. I still use Karma and Phantom JS for front end testing and it works really well.

 

Having said that, my understanding is that there may be some advantage to using Jest for testing React components due to the snapshot testing functionality that comes with Jest. I've not tried it so don't have much perspective yet. Tape I've never seen the point in - Eric Elliot seems to like it, but when I read his reasons they didn't really make much sense to me - the article he wrote on the subject didn't really expose any issues that I've actually encountered using those tools, so I've continued to use them without issue.

 

I've heard AVA is supposed to be quite nice, and one of the advantages of this framework is that it can run tests in parallel, but having said that, unit tests are usually so fast that you'll probably not notice much difference.

 

One tool I would definitely recommend is Wallaby.js - unfortunately though it's paid for software, and their license isn't the best. It is by far the best test runner I know of though, and I reckon it makes me significantly faster in my daily job. It works with basically all the tools mentioned above (and many more), and integrates directly into your editor of choice. It's a godsend, and despite their rubbish license model, I think it's worth purchasing.

 

I'd recommend getting to grips with the flow of TDD before playing about with the different tools. Mocha and Chai are a classic combination and they work very well. Once you've got to grips with the general flow of TDD and how it fits together, then maybe play about with the different frameworks to se what you think. They all basically do the same thing anyway.

 

Thanks, Paul.

  • Author

To be honest, in a lot of these cases it tends to be that people like to use the tools they're used to. Some of the tools may have advantages over others, but I've personally seen little reason to move from Mocha/Chai and Jasmine for most JS stuff in general. I still use Karma and Phantom JS for front end testing and it works really well.

 

Having said that, my understanding is that there may be some advantage to using Jest for testing React components due to the snapshot testing functionality that comes with Jest. I've not tried it so don't have much perspective yet. Tape I've never seen the point in - Eric Elliot seems to like it, but when I read his reasons they didn't really make much sense to me - the article he wrote on the subject didn't really expose any issues that I've actually encountered using those tools, so I've continued to use them without issue.

 

I've heard AVA is supposed to be quite nice, and one of the advantages of this framework is that it can run tests in parallel, but having said that, unit tests are usually so fast that you'll probably not notice much difference.

 

One tool I would definitely recommend is Wallaby.js - unfortunately though it's paid for software, and their license isn't the best. It is by far the best test runner I know of though, and I reckon it makes me significantly faster in my daily job. It works with basically all the tools mentioned above (and many more), and integrates directly into your editor of choice. It's a godsend, and despite their rubbish license model, I think it's worth purchasing.

 

I'd recommend getting to grips with the flow of TDD before playing about with the different tools. Mocha and Chai are a classic combination and they work very well. Once you've got to grips with the general flow of TDD and how it fits together, then maybe play about with the different frameworks to se what you think. They all basically do the same thing anyway.

 

Yeah, I really like Mocha and Chai, I understood the API straight-away. A couple of things I can't work out, though, like how would you test something like setTimeout or setInterval?

Guest
This topic is now closed to further replies.

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.